1.0.1 • Published 4 years ago

@js-studio/development-api-interceptor v1.0.1

Weekly downloads
-
License
-
Repository
github
Last release
4 years ago

Development API Interceptor

This package creates a mock RESTful API backend and also generates an IndexedDB database in the client from the provided JSON representation which in turn helps to speed up the development process.

Note: This package has been developed and tested for React client-side Application. Hence will only work with React.

Getting Started

The below instructions will help you in installing the package into the Client application. See Usage for notes on how to use the basic functionalities of the package.

Installation and Setup

Step 1

Install the package in the Client Application(React).

npm install @jsstudio/development-api-interceptor --save-dev
Step 2

Create a db.json file based on the below JSON Schema and JSON Representation Example. JSON Schema

{
    "database": "[Database Version]",
    "tables": [
        {
            "table_name": "[Table name]",
            "columns": [
                {
                    "entity_name": "[Entity name]",
                    "type": "[string, number, boolean, date, array, object]",
                    "keys": [array], //Only if entity type is object
                    "primary_key": boolean, //One column must be a primary key
                    "auto_increment": boolean, //Only primary key column must have auto increment key
                    "constraints": {
                        MAX_LENGTH: [NUMBER],
                        NOT_NULL: [BOOLEAN],
                        MIN_LENGTH : [NUMBER]
                    }
                },
            ]
        }
}

JSON Representation Example

{
    "database": "db-v1",
    "tables": [
        {
            "table_name": "employees",
            "columns": [
                {
                    "entity_name": "name",
                    "type": "string",
                    "constraints": {
                        "MAX_LENGTH": 30,
                        "NOT_NULL": true
                    }
                },
                {
                    "entity_name": "id",
                    "primary_key": true,
                    "auto_increment": true,
                    "type": "number",
                    "constraints": {
                        "MAX_LENGTH": 4,
                        "NOT_NULL": false
                    }
                },
                {
                    "entity_name": "details",
                    "type": "object",
                    "keys": [
                        {
                            "entity_name": "mobile",
                            "type": "number",
                            "constraints": {
                                "MAX_LENGTH": 10000000000,
                                "NOT_NULL": true
                            }
                        },
                        {
                            "entity_name": "dob",
                            "type": "date",
                            "constraints": {
                                "MAX_LENGTH": "12-31-2020",
                                "NOT_NULL": true
                            }
                        },
                        {
                            "entity_name": "project",
                            "type": "boolean"
                        }
                    ]
                },
                {
                    "entity_name": "designation",
                    "type": "string",
                    "constraints": {
                        "MAX_LENGTH": 20,
                        "NOT_NULL": true
                    }
                }
            ]
        },
        {
            "table_name": "projects",
            "columns": [
                {
                    "entity_name": "project_name",
                    "type": "string",
                    "constraints": {
                        "MAX_LENGTH": 32,
                        "NOT_NULL": true
                    }
                },
                {
                    "entity_name": "id",
                    "primary_key": true,
                    "type": "number",
                    "constraints": {
                        "MAX_LENGTH": 4,
                        "NOT_NULL": true
                    }
                },
                {
                    "entity_type": "foreign_key",
                    "foreign_key_table_column": "id",
                    "table_name": "employees",
                    "type": "number",
                    "entity_name": "employee_id"
                }
            ]
        }
    ]
}
Note:
  • Each table must have a primary key. If a primary key is not specified, the user would get an error - 'The object store uses out-of-line keys and has no key generator and the key parameter was not provided.' or 'Data provided to an operation does not meet requirements' on subsequent interceptor operations.
  • The primary key constraint NOT_NULL must be true if auto_increment is false.
  • The auto_increment can be only set to true for the column that is a primary key and is of type number else auto Increment feature would not work.
  • The primary key constraint NOT_NULL can be false if auto_increment is true.
  • Type in foreign key must be equal to the type of column it is referring to.
  • Type of foreign key can not be an object.
  • If the type of entity is an object, it must include a key keys which would be an array containing the keys of the object.
  • If the schema is to be changed in the future, it must be accompanied by a change in database key. For eg.- If there is any change in employees table in the future, then the database name needs to be changed in the JSON and it could be "database": "db-v2".
Step 3

Import the package inside the Client Application in App.js file. For Axios Library

import axios from 'axios';
import createMockApi from '@jsstudio/jsstudio-react-mock-api';
import json from {jsonSchemaFile};
createMockApi(json, axios);

For Fetch Library

import createMockApi from '@jsstudio/jsstudio-react-mock-api';
import json from {jsonSchemaFile};
createMockApi(json);

Output : Below indexedDB database will be created using example json representation.

Routes

Intercepts the following requests-

GET    /api/{tablename}
GET    /api/{tablename}/{id}
POST   /api/{tablename}
PUT    /api/{tablename}
DELETE /api/{tablename}/{id}

Usage

Using Axios Library -

// Axios get all request
  const result = await axios.get('/api/{tablename}');
  Eg. - axios.get('/api/employees');
        axios.get('/api/projects');
  
// Axios get request
  const result = await axios.get('/api/{tablename}/{id}');
  Eg. - axios.get('/api/employees/1');
        axios.get('/api/projects/1');
  
// Axios post request
  const result = await axios.post('/api/{tablename}', {body});
  Eg. - axios.post('/api/employees', { name: 'John Doe', details: { mobile: 1234567890, dob: '01-31-1970', project: true}, designation: 'Software Developer' };
        axios.post('/api/projects, { id : 1, project_name: 'Project X', employee_id: 1};

// Axios put request
  const result = await axios.post('/api/{tablename}', {body});
   Eg. - axios.post('/api/employees', { name: 'John Doe Jr', details: { mobile: 1234567890, dob: '01-31-1970', project: true}, designation: 'Software Developer' };
          axios.post('/api/projects, { id : 1, project_name: 'Project Y', employee_id: 1};
  
// Axios delete request
  const result = await axios.post('/api/{tablename}/{id}');
  Eg. - axios.delete('/api/employees/1');
        axios.delete('/api/projects/1');

Using Fetch - Always pass the config while using fetch api. Below is the sample code.

// Fetch api get request
 const getOptions = {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' },
  };
  const result = await fetch('/api/employees', getOptions)
  const text = await result.text()

// Fetch api post request
const postOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: { name:'mohit', details: { mobile: 1231231, dob: '01-01-1970', project :true }, designation: 'dev' }
};
var response = await fetch('/api/employees', postOptions);
var body = await response.json();

Package Import Suggestion

Since it is a dev package, create src/config/environment/development.js and paste the below code in that file.

import axios from 'axios'
import createMockApi from '@jsstudio/jsstudio-react-mock-api';
import json from {jsonSchemaFile};

export createMockApi(json, axios);

And then import the file into the main src/App.js file according to the development or test environment.

Features

  • Creating backend kind of functionality without using a backend.
  • Generating version based indexedDB database.
  • Intercepting API request to fetch the data from indexedDB using Fetch or Axios interceptor.
  • Performing RESTful API functions.

Technologies Used

  • Languages : Typescript
  • Database: IndexedDB
  • Client : React
  • Validation Library: Joi, Ajv
  • Logger Library : Logger
  • Interceptor Library : Fetch and Axios
  • Unit Test Cases : Mocha and Chai

Author

👤 srijanone

Show your support

Give a ⭐️ if this project helped you!

License

(c) Copyright JSSTUDIO Inc. 2020