HTML and CSS Reference
In-Depth Information
function setupDatabase() {
db = openDatabase('tweets', '1.0', 'db of tweets',
¬ 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE tweets (id unique,
¬ screen_name, date integer, text)');
});
getTweets();
}
A few things to note about the code are
1.
I'm using a global
db
variable. (I'm just using a global for the
contrived example; global is generally bad in JavaScript.)
2.
I'm telling the tweets database that the
id
column is
unique. This means if there's a duplicate
INSERT
attempt,
the
INSERT
fails.
3.
If the
CREATE TABLE
fails, it's fine because it will fail only
when the table already exists, and you're not doing any-
thing else in that transaction.
4.
Once it's done, I call
getTweets
, which will make the API
request to Twitter, which will in turn call the storing function.
What if
getTweets
runs before the table gets created? It doesn't
matter. That's because when we get the tweets, a new transac-
tion is created that inserts the new SQL. Since transactions run
in the order they were sent to the database, even if the create
table hasn't actually run when we're creating transactions to
insert new rows, we know that it's queued ahead of the new
rows and will be there all in good time.
The
forEach
in the following code is a new JavaScript method
available in all the latest browsers, allowing you to loop through
an array. Mozilla's site provides simple code for implementing
this in browsers that don't have it natively:
https://developer.
Array/forEach
. Once the Twitter API call completes, it will call
saveTweets
, which will store each of the tweets:
function saveTweets(tweets) {
tweets.results.forEach(function (tweet) {
db.transaction(function (tx) {
var time = (new Date(Date.parse(tweet.created_at))).
¬ getTime();
tx.executeSql('INSERT INTO tweets (id, screen_name,
¬ date, text) VALUES (?, ?, ?, ?)', [tweet.id,
¬ tweet.from_user, time / 1000, tweet.text]);
NoTE
Yo u ' r e c r e a t i n g a
new transaction for each
stored tweet. I'll explain transac-
tions in more detail in the next
section, but by wrapping individ-
ual
INSERT
statements you're
ensuring that all the new tweets
are stored, irrespective of
whether you already have these
in the database.