@bcm-energy/bcm-api-generator

Template Generator for nodejs API

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
@bcm-energy/bcm-api-generator
1.3.05 years ago6 years agoMinified + gzip package size for @bcm-energy/bcm-api-generator in KB

Readme

BCM API Generator

Version 1.3.0
The BCM API Generator is the tool to generate BCM Energy & Planète OUI backend architecture APIs.

Documentation
· Guide for unit tests
The documentation, readme and guide assume that you are working on an unix like environnement

Summary

  1. Usage
1. **Installation**
2. **Usage**
3. **Update & Publish NPM Script**
  1. Usage with the WebAPP
Documentation
1. **Run API**
2. **API Endpoints**
3. **SQL Database**
    1. **Launch Database**
    2. **Use Database in API**
4. **Services**
5. **Linter**
6. **Production mode**
7. **End to end Test**
8. **Route Parameter Validation Middleware**
  1. Unit testing

  1. Usage with NPM

1. **Installation**

    The first thing to do is to install the package as global on your computer :

    ```bash
    npm install -g @bcm-energy/bcm-api-generator
    ```

    It should be the last version by default (currently **1.3.0**), but if it's not you can force installation by using this command :

    ```bash
    npm install -g @bcm-energy/bcm-api-generator@1.3.0
    ```

2. **Usage**

    Then you just have to launch the script that will generate a simple project:

    ```bash
    bcm-gen <folder path>
    ```

    **⚠️ Be careful, if you launch the script on an existing folder, files with the same name as those generated by the script will be erased**

    If the folder does not exists, it will be automatically created. If it already exists, make sure you have the right to write on this folder.

    You can also add more option to the project like

    <br/>
    Adding a database

    ```bash
    bcm-gen <folder path> --db=<mysql|pg>
    ```

    <br/> 
    Adding Listeners

    ```bash
    bcm-gen <folder path> --hasListeners
    ```

    <br/> 
    Adding e2e test

    ```bash
    bcm-gen <folder path> --e2e
    ```

    <br/> 
    Adding ESP option on the k8s file

    ```bash
    bcm-gen <folder path> --hasESP
    ```

    <br/>

3. **Update & Publish NPM Script**

    If you want to publish an update, git clone the repository (https://github.com/BCM-ENERGY-team/bcm-api-generator), make your changes and create a pull request.
  1. Usage with the webApp

To use the web app you can directely access it through this URL  

http://start.beta.bcmenergy.fr/

Or you can clone this project and launch it locally with the following commands :

```bash
npm run dev
```

or

```bash
npm start
```
  1. Documentation to launch the generated api

1. **Run API**

    To launch the API you just need to run :

    ```bash
    npm run dev
    ```

2. **API Endpoints**

    If you want to add an endpoint to your api, you just have to create a folder in `app/api/your_folder/`  and create the file `index.js` inside this folder.

    ***./app/api/your_folder/index.js :***

    ```javascript
    module.exports = app => {
        app.get('/your_route', (req, res) => {
            res.status(200).send("Hello World");
        });
    }
    ```

    Then you have to edit the index.js file located on root folder and add the line to require your route folder.

    *./**index.js** :*

    ```javascript
    // ROUTER (line 15)
    ...
    require('./app/api/your_folder'); // <-- Your route file
    ```

    Test the route :

    ```bash
    curl http://127.0.0.1:3000/your_route # print Hello World
    ```

3. **SQL Database**

    1. **Launch Database**

        By default the API does not have a database you will need to add the db option.

        To launch the postgres database, run :

        ```bash
        npm run test-db
        ```

        This script will create a postgres docker container, it will also execute all the .sql files located in `./test/sql/`

        You just have to create or edit these files to run your own sql script.

    2. **Use Database in API**

        Make sure that you Env variables DB_HOST, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT

        To make queries to the database, you have to require the connection file `../../database/postgres/db`.

        Example :

        ```javascript
        const db = require('../../database/postgres/db')(require('../../config'));

        let data = await db('t_trades').select('*'); // Asynchronous
        ```

        See <a href="https://knexjs.org/">knex</a> documentation for more.

4. **Services**

    The services folder is where you put your sources files that are not related to the database and that can be reused for others parts of your app.

5. **Linter**

    To ensure that all of our APIs are formatted the same way, we use eslint, it's already configured, so you just have to run :

    ```bash
    npm run lint # print your errors
    npm run lint-fix # eslint can automatically fix some errors.
    ```

6. **Production mode**

    While it's unlikely that you need this feature, it's possible to run the application in production mode :

    ```bash
    npm start
    ```

7. **End to end Test**

    If you added the e2e parameter you will have a directory with the name e2e.
    In this directory you will put all your end to end test. The end to end test file name should respect the following format nameOfThetest **.e2e.test.js**

    To run the e2e test you have to run :

    ```bash
    npm run test-e2e
    ```

8. **Route Parameter Validation Middleware**

    The API Generated has also a middleware that will allow you to validate the body of your different routes

    You will need to call the validate fucnction with a JSON Schema.
    **JSON Schema**  is a vocabulary that allows you to annotate and validate JSON documentation. You can find more inforamtions on https://json-schema.org/

    ```javascript
    const validate = require('../../middlewares/validate');

        app.get('/test', validate(require('./schemas/test.json')), async (req, res) => {...
    ```
  1. Unit testing

There are two ways to test the application :

- Running the whole test suite in a dockerized stack
- Running locally the test suite with a dockerized database

### Fully dockerized

This is what will be run as part of the CI build validation. Running it can be achieved by doing:

```sh
docker-compose up --force-recreate --build --abort-on-container-exit db-for-docker-test api-for-docker-test
```

Or simply through:

```bash
npm run test-docker
```

This will spawn a database instance in a docker and the test will be run in a companion docker instance.

### Only database in container

This is useful when we need to run tests often. Using this option, only the database is deployed in a container. One only needs to perform:

```sh
docker-compose up --force-recreate --build --abort-on-container-exit db-for-docker-test
```

The database can also be launched using:

```sh
npm run test-db
```

Contrary to running the database with docker-compose, when it's launched using npm, the containers are in background mode.

When the database is up and running, one can run the test suite by doing:

```sh
npm run test
```

You may need to adjust your environment variables to point to this database instance.

You will have a env file where you will find the password for the test database

### Coverage

Along with testing the application, a good indicator is the test coverage.

There are two ways to get the coverage

#### Text mode

```sh
npm run coverage
```

You'll get a text output on the console showing the actual coverage.
Something similar to:

![Text mode](docs/img/istanbul-text.png)

### HTML mode

```sh
npm run coverage-html
```

You then need to open the `output/index.html` file to get a browsable HTML report such as:

![HTML mode](docs/img/istanbul-html.png)