Tuesday, December 24, 2019

Swagger UI for ExpressJS

Swagger is a tool that allows to describe a service API. One of the reasons for that is creation of documentation for all API functions so make it easy to examine and navigate through. Even further, swagger allows to call the API functions in a simple manner like let's say Postman does. So working with ExpressJS I just discovered the swagger-ui-express library that gives us opportunity to build the swagger UI in literaly few steps. So I created the simplest possible example (Github Link) that will be be taken to pieces below step-by-step.

As usually, we start with installing the package npm install -s swagger-ui-express.

Now let's create a simple ExpressJS HTTP server with several CRUD functions.

const express = require('express');
const app = express();

const uuidv4 = require('uuid/v4');

//stores the books collection
let _books = [];

app.route('/api/book')
    .get(function (req, res) {
        res.json(_books.filter(b => b.id == req.query.id));
    })
    .put(function (req, res) {
        let book = JSON.parse(JSON.stringify(req.query));
        book.id = uuidv4();
        _books.push(book);
        res.json(book);
    })
    .delete(function (req, res) {
        _books = _books.filter(b => b.id != req.query.id);
        res.json(_books);
    })

app.get('/api/books', function (req, res) {
    res.json(_books);
});


// start the server in the port 3000
app.listen(3000, function () {
    console.log('Start app listening on port 3000.');
});

The service exposes functions allow to get/add/delete records (books) and retrieve all the books as well.

Next step is to display that API on UI.

Tuesday, December 3, 2019

Update styles in bulk via JavaScript

Updating an element style using javascript is pretty easy: document.getElementById(id).style.property = new style. But what if we have hundreds/thousands/.. elements to be updated? Calling the property setter above will force page re-rendering every time, so it would take considerable time. That's where bulk update is really helpful. Instead of applying styles after every change we can compose the css sheet with all the styles collected together and appy it at once.