Categories
JavaScript JavaScript Basics

Add a Timer to Run Code Between Specified Time Intervals With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setInterval function lets us run code after a given delay in milliseconds repeatedly. It’s queued to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setInterval(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setInterval function and a 1000 ms interval as the second argument.

Then we should see 'hi' logged in the console log output after every second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setInterval((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setInterval, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setInterval also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setInterval if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearInterval function which takes the timer ID object that’s returned by setInterval.

For instance, we can do that as follows:

const timer = setInterval((greeting) => console.log(greeting), 1000, 'hi');
clearInterval(timer);

Since we called clearInterval immediately after calling setInterval, the callback won’t be called since we disposed of our timer with clearInterval.

Categories
JavaScript JavaScript Basics

Add a Timer With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setTimeout function lets us run code after a given delay in milliseconds. It’s queue to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setTimeout(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setTimeout function and a 1000 ms delay as the second argument.

Then we should see 'hi' logged in the console log output after 1 second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setTimeout((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setTimeout, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setTimeout also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setTimeout if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearTimeout function which takes the timer ID object that’s returned by setTimeout.

For instance, we can do that as follows:

const timer = setTimeout((greeting) => console.log(greeting), 1000, 'hi');
clearTimeout(timer);

Since we called clearTimeout immediately after calling setTimeout, the callback won’t be called since we disposed of our timer with clearTimeout.

Categories
JavaScript Rxjs

Rxjs Filtering Operators — Skip and Take

Rxjs is a library for doing reactive programming. Creation operators are useful for generating data from various data sources to be subscribed to by Observers.

In this article, we’ll look at more filtering operators, including skipUntil, skipWhile, take, takeLast, takeUntil, and takeWhile operators.

skipUntil

The skipUntil operator returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.

It takes one argument, which is the notifer Observable. When this emits an item, then the source Observable’s emitted values will be emitted by the skipUntil operator.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { skipUntil, take } from "rxjs/operators";

const numbers = interval(1000).pipe(  
  take(10),  
  skipUntil(interval(5000).pipe(take(1)))  
);  
numbers.subscribe(x => console.log(x));

The code above takes the emitted values from the interval(1000) Observabkem then pipe it to the take(10) operator to take the first 10 values, then take those values to the skipUntil operator, which has the interval(5000).pipe(take(1)) Observable passed in.

interval(5000).pipe(take(1)) emits a value after 5 seconds, which then will trigger the emission of the interval(1000) Observable’s emitted values.

Then we should see:

4  
5  
6  
7  
8  
9

skipWhile

The skipWhile operator returns an Observable that skips all items emitted by the source Observable until the condition returned by the predicate function becomes false.

It takes one argument, which is a predicate function to test each item with the condition returned by the function.

For example, we can write the following:

import { of } from "rxjs";  
import { skipWhile } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5, 6).pipe(skipWhile(x => x < 3));  
numbers.subscribe(x => console.log(x));

Then the items from the of(1, 2, 3, 4, 5, 6) Observable won’t be emitted when the value is less than 3. This means that numbers will emit 3, 4, 5 and 6.

Once the condition in the predicate function is tested false once, it’ll keep emitting regardless whether the emitted value from the source Observable make the condition evaluate to false or not.

So if we have:

import { of } from "rxjs";  
import { skipWhile } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 3, 2).pipe(skipWhile(x => x < 3));  
numbers.subscribe(x => console.log(x));

Then we get 3, 4, 5 and 2 since the condition becomes false once the first 3 was emitted by of(1, 2, 3, 4, 3, 2).

take

The take operator returns an Observable that emits the first count values emitted by the source Observable.

It takes one argument which is the count, which the maximum number of values to emit.

For example, we can use it as follows:

import { of } from "rxjs";  
import { take } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 3, 2).pipe(take(2));  
numbers.subscribe(x => console.log(x));

Then we get 1 and 2 logged since we passed 2 into the take operator.

takeLast

The takeLast operator returns an Observable that emits the last count values emitted by the source Observable.

It takes one argument which is the count, which the maximum number of values to emit from the end of the sequence of values.

For instance, we can use it as follows:

import { of } from "rxjs";  
import { takeLast } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5, 6).pipe(takeLast(2));  
numbers.subscribe(x => console.log(x));

We should get 5 and 6 since we passed in 2 to the takeLast operator, which means we only want the last 2 values from the of(1, 2, 3, 4, 5, 6) Observable emitted.

takeUntil

The takeUntil operator returns an Observable that emits value from the source Observable until the notifier Observable emits a value.

It takes one argument, which is the notifier whose emitted value will cause the return Observable to stop emitting values from the source Observable.

For example, we can use it as follows:

import { interval, timer } from "rxjs";  
import { takeUntil } from "rxjs/operators";

const source = interval(1000);  
const result = source.pipe(takeUntil(timer(5000)));  
result.subscribe(x => console.log(x));

The code above will emit the values from the source Observable until timer(5000) emits its first value.

So we should get something like:

0  
1  
2  
3

takeWhile

The takeWhile operator returns an Observable that emits the values emitted by the source Observable as long as the condition in the predicate function is satisfied and completes as soon as the condition is not satisfied.

It takes of argument, which is the predicate function that returns the condition to check each value from the source Observable with. The function takes the item from the source Observable as the first parameter and the index, starting from 0, of the value emitted as the second parameter.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { takeWhile } from "rxjs/operators";

const source = interval(1000);  
const result = source.pipe(takeWhile(x => x <= 10));  
result.subscribe(x => console.log(x));

Then we should get:

0  
1  
2  
3  
4  
5  
6  
7  
8  
9  
10

since we specified in the predicate function that x => x <= 10, which means that any value less than or equal to 10 from the source Observable will be emitted.

The skipUntil operator returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.

skipWhile operator returns an Observable that skips all items emitted by the source Observable until the condition passed into the predicate function becomes false

The take operator returns an Observable that emits the first number of values emitted by the source Observable.

The takeLast operator returns an Observable that emits the last number of values emitted by the source Observable.

takeUntil operator returns an Observable that emits value from the source Observable until the Observable passed into this operator emits a value.

Finally, the takeWhile operator returns an Observable that emits the values emitted by the source Observable as long as the condition passed into this is satisfied.

Categories
Express JavaScript Testing

Adding Database Interactions to Express Apps

Most back end apps need to interact with a database to do something useful. With Express apps, we can add database interactivity easily.

In this article, we’ll look at how to get and save data into an SQLite database with an Express app.

Getting Started

We get started by creating a project folder, then go in it and run:

npm init -y

to create a package.json file.

The -y flag just answers all the question from npm init with the default options.

Next, we install Express, body-parser to parse request bodies, and sqlite3 for interacting with our SQLite database by running:

npm i express sqlite3 body-parser

Building Our App

Initialization Code

The app we build will get and save data to the persons database.

To start, we create an app.js for the app. Then we create the app by first importing the packages we need to use and setting the port that our app will listen to connections to.

To do this, we add:

const express = require('express');  
const sqlite3 = require('sqlite3').verbose();  
const bodyParser = require('body-parser');  
const app = express();  
const port = 3000;

We include the packages we installed earlier, including Express, body-parser , and sqlite3 .

Then we create an instance of our Express app and set the port to 3000 to listen to requests on port 3000.

Next, we create our database initialization code. We do this by writing:

const db = new sqlite3.Database('db.sqlite');

The code above tells us that our app will use db.sqlite to get and save data. If it doesn’t exist, it’ll be created on the fly so we don’t have to create it beforehand. Also, we don’t need any credentials to use the database file.

Then we create the person table if it doesn’t already exist by writing:

db.serialize(() => {  
    db.run('CREATE TABLE IF NOT EXISTS persons (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');  
});

We have an id auto-incrementing integer column, and name and age columns for saving some personal data.

We include IF NOT EXISTS in our CREATE TABLE query so that the database won’t be attempted to be created every time the app restarts. Since if it already exists, the query will fail if the table already exists.

Then we include our body-parser middleware so that JSON request bodies will be parsed into the req.body object as follows:

app.use(bodyParser.json());

Adding the Routes

Now we add the routes for getting and saving data.

First, we add a route to handle GET requests for getting data from the persons table, we add the following:

app.get('/', (req, res) => {  
    db.serialize(() => {  
        db.all('SELECT * FROM persons', [], (err, rows) => {  
            res.json(rows);  
        });  
    })  
})

We use app.get to handle the GET request to the / route.

db.serialize makes sure that each query inside the callback runs in sequence.

Then we select all the rows from the persons table and send the array returned as the response.

Next, we add our POST route to handle the POST request for saving a new entry to the database:

app.post('/', (req, res) => {  
    const { name, age } = req.body;  
    db.serialize(() => {  
        const stmt = db.prepare('INSERT INTO persons (name, age) VALUES (?, ?)');  
        stmt.run(name, age);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

We start by using the app.post to indicate that we’re handling a POST request. The / means that we’ll handle requests to the / path.

Next, we get the parsed JSON request body returned by body-parser by writing:

const { name, age } = req.body;

We decomposed the fields into variables with the destructing assignment operator.

Next, we create a prepared statement to insert data to the persons table with db.prepare. This lets us set data for the placeholders marked by the ? and also sanitizes the data to avoid SQL injection attacks.

Then we run:

stmt.run(name, age);  
stmt.finalize();

to run the statement and return the response with res.json(req.body); .

Next, we add the route to let us update an entry:

app.put('/:id', (req, res) => {  
    const { name, age } = req.body;  
    const { id } = req.params;  
    db.serialize(() => {  
        const stmt = db.prepare('UPDATE persons SET name = ?, age = ? WHERE id = ?');  
        stmt.run(name, age, id);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

It’s similar to the POST request route above, except that we’re handling PUT requests.

The difference is that we have an :id in the URL parameter, which we get by writing:

const { id } = req.params;

So when we make a request to /1 , id will be set to 1.

Then we ran our update statement with name , age , and id and return the request body as the response.

Finally, we have our DELETE route to let us delete items from the persons table as follows:

app.delete('/:id', (req, res) => {  
    const { id } = req.params;  
    db.serialize(() => {  
        const stmt = db.prepare('DELETE FROM persons WHERE id = ?');  
        stmt.run(id);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

It’s similar to the other routes except that we have a delete request and we run a delete statement with the ID.

Then we return the request body as the response.

Finally, we add the following line:

const server = app.listen(port);

So that when we run node app.js , our app will run.

Conclusion

We run our app by running node app.js .

In the end, we have the following code if we put everything together:

const express = require('express');  
const sqlite3 = require('sqlite3').verbose();  
const bodyParser = require('body-parser');  
const app = express();  
const port = 3000;  
const db = new sqlite3.Database('db.sqlite');
db.serialize(() => {  
    db.run('CREATE TABLE IF NOT EXISTS persons (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');  
});

app.use(bodyParser.json());  
app.get('/', (req, res) => {  
    db.serialize(() => {  
        db.all('SELECT * FROM persons', [], (err, rows) => {  
            res.json(rows);  
        });  
    })  
})

app.post('/', (req, res) => {  
    const { name, age } = req.body;  
    db.serialize(() => {  
        const stmt = db.prepare('INSERT INTO persons (name, age) VALUES (?, ?)');  
        stmt.run(name, age);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

app.put('/:id', (req, res) => {  
    const { name, age } = req.body;  
    const { id } = req.params;  
    db.serialize(() => {  
        const stmt = db.prepare('UPDATE persons SET name = ?, age = ? WHERE id = ?');  
        stmt.run(name, age, id);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

app.delete('/:id', (req, res) => {  
    const { id } = req.params;  
    db.serialize(() => {  
        const stmt = db.prepare('DELETE FROM persons WHERE id = ?');  
        stmt.run(id);  
        stmt.finalize();  
        res.json(req.body);  
    })  
})

const server = app.listen(port);

Once we include a database library, we can create an Express app that interacts with a database to make our apps more useful.

Categories
JavaScript Rxjs

Rxjs Filtering Operators — Sample, Skip and Single

RxJS is a library for doing reactive programming. Creating operators are useful for generating data from various data sources to be subscribed to by Observers.

In this article, we’ll look at some filtering operators, including sample, sampleTime,skip, single, and skipLast operators.

sample

The sample operator returns an Observable that emits the value from the source Observable when the notifier Observable emits.

It takes one argument, which is the notifer Observable.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { sample } from "rxjs/operators";
const seconds = interval(1000);  
const result = seconds.pipe(sample(interval(5000)));  
result.subscribe(x => console.log(x));

In the code above, we have the seconds Observable which emits a number every second. Then we pipe the result of it to the sample operator, where we set the notifier Observable which is interval(5000), which emits every 5 seconds.

Therefore, we have a new Observable that emits values from seconds every 5 seconds.

We should see every few values from seconds logged.

sampleTime

The sampleTime operator emits the most recently emitted value from the source Observable in periodic intervals.

It takes up to 2 arguments. The first is the period, which is the period to wait until emitting a value from the source Observable. It’s measured in milliseconds or the time unit of the optional scheduler .

The second argument is the optional scheduler, which defaults to async.

It returns a new Observable that emits value from the source Observable in a specified time interval.

For example, we can use it as follows:

import { interval } from "rxjs";  
import { sampleTime } from "rxjs/operators";
const seconds = interval(1000);  
const result = seconds.pipe(sampleTime(5000));  
result.subscribe(x => console.log(x));

The code above takes the values emitted from the seconds Observable and pipe it to the sampleTime operator, which will emit values from seconds every 5 seconds.

The result will be that we get values emitted from the result Observable, which gets its values from the seconds Observable, every 5 seconds.

We should see some numbers logged from the console.log .

single

single returns an Observable that emits the single item from the source Observable that matches a given condition returned by the predicate function.

If the source Observable emits more than one of such item or no items, then we get IllegalArgumentException or NoSuchElementException respectively.

If the source Observable emits items but none match the condition in the predicate function then undefined is emitted.

It takes one argument, which is the predicate function that returns the condition to match the item emitted from the source Observable.

For example, if we have:

import { of } from "rxjs";  
import { single } from "rxjs/operators";
const numbers = of(1).pipe(single());  
numbers.subscribe(x => console.log(x));

Then we get 1 logged.

If we have:

import { of } from "rxjs";  
import { single } from "rxjs/operators";
const numbers = of(1, 2).pipe(single());  
numbers.subscribe(x => console.log(x));

Then we get the error “Sequence contains more than one element” logged.

If we have:

import { of } from "rxjs";  
import { single } from "rxjs/operators";
const numbers = of(1, 2).pipe(single(x => x % 2 === 0));  
numbers.subscribe(x => console.log(x));

Then we get 2 logged since 2 matches the condition x => x % 2 === 0 .

skip

The skip operator returns an Observable that skips the first count items emitted by the source Observable and emit the rest.

It takes the required count argument, which is the number of items from the source Observable to skip.

For example, if we have:

import { of } from "rxjs";  
import { skip } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5).pipe(skip(2));  
numbers.subscribe(x => console.log(x));

Then we get:

3  
4  
5

logged because we specified that we want to skip the first 2 emitted values from of(1, 2, 3, 4, 5) .

skipLast

The skipLast operator returns an Observable that skips the last count values emitted from the source Observable.

It takes the required count argument, which is the number of items from the source Observable to skip from the end of the source Observable.

For example, we can write:

import { of } from "rxjs";  
import { skipLast } from "rxjs/operators";

const numbers = of(1, 2, 3, 4, 5).pipe(skipLast(2));  
numbers.subscribe(x => console.log(x));

Then we get:

1  
2  
3

logged since we specified that we want to skip the last 2 emitted values.

The sample and sampleTime operators return an Observable that emits the value from the source Observable when the notifier Observable emits or at the specified time interval respectively.

single returns an Observable that emits the single item from the source Observable that matches a given condition.

The skip operator returns an Observable that skips the number of items at the start of emitting the values from the Observable.

Finally, skipLast operator returns an Observable that skips the last number of values emitted from the source Observable.