HTML and CSS Reference
In-Depth Information
is integer—which is important to allow you to query the data-
base later on in your application:
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 fi ne because it will only fail
because 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.
The
forEach
method 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:
Reference/Global_Objects/Array/forEach
.
Once the Twitter API
call completes it will call
saveTweets
, which will do the storing of
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]);
// div 1000 to get to seconds
});
});
}
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.