2.0.9 • Published 2 years ago

@discovery-solutions/json-server v2.0.9

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

JSON Server

This library allows you to create multiple API servers with minimum amount of code or setup, using a JSON configuration.

The generated API can handle simple CRUD of entities to authentication, and much more. Check the documentation bellow.

To understand the endpoints generated by the API, check this section.

CHECK COMPLETE EXAMPLE

Installation

Run the following command:

npm install --save @discovery-solutions/json-server

If you want to use features like connection with MongoDB or JWT for authentication, you should install those libraries:

npm install --save mongodb
npm install --save jsonwebtoken

Basic Setup

import Server from "@discovery-solutions/json-server";

const server = new Server({
  name: "my-server",
  config: {
    port: 3500,
    type: "rest",
    format: "json",
  },
  database: {
    type: "custom",
    key: "my-db-1",
    name: "my-custom-db"
  },
  entities: [{
    name: "user",
    alias: "User",
    fields: {
      name: {
        type: "string",
        required: true
      },
      email: {
        type: "string",
        required: true
      },
      password: {
        type: "string",
        required: true
      },
      phone: "string",
      birthdate: "date",
      avatar: "image"
    }
  }]
});

server.run();

Or you could also, save this into a JSON file (it must be called server.json), and run the following command to start the server:

npx json-server

The file should look like this:

{
  "name": "my-server",
  "config": {
    "port": 3500,
    "type": "rest",
    "format": "json"
  },
  "database": {
    "type": "custom",
    "key": "my-db-1",
    "name": "my-custom-db"
  },
  "entities": [
    {
      "name": "user",
      "alias": "User",
      "fields": {
        "name": {
          "type": "string",
          "required": true
        },
        "email": {
          "type": "string",
          "required": true
        },
        "password": {
          "type": "string",
          "required": true
        },
        "phone": "string",
        "birthdate": "date",
        "avatar": "image"
      }
    }
  ]
}

Parameters

Parameter KeyDescriptionRequiredDefault Value
nameThe server project nametrue
labelLabel displayed at API Docsfalsevalue of name
corsCORS Setupfalsefalse
configSetup of the serverstrue
databaseDatabase setupfalsenative
entitiesEntities for CRUD featurestrue

name

The simplest of all the parameters, just an identifyer for your project. This should be an string, like the example below:

const server = new Server({
  name: "my-server",
  // ...
});

label

This is a label to display at API Autogenerated Docs.

const server = new Server({
  name: "my-server",
  label: "My Server Project"
  // ...
});

cors

This is flag to allow CORS.

const server = new Server({
  // ...
  cors: true,
  // ...
});

config

This could a simple object for one server, or an array of objects for multiple servers configuration.

KeyDescriptionType or OptionsRequired
portnumber of the port the server should runnumbertrue
databasethe database key the server should usestringtrue
formatformat of the responsesjson, csv
typetype of the serverrest, socket
requestsettings for requestsobject

Complete example:

const server = new Server({
  // ...
  config: {
    port: 3500,
    type: "rest",
    format: "json",
    database: "my-db-1",
    request: {
      limit: 10,
    },
  }
});

Multiple servers example

const server = new Server({
  // ...
  config: [{
    port: 3501,
    type: "rest",
    database: "my-db-1",
    format: "json",
  }, {
    port: 3501,
    type: "socket",
    database: "my-db-2",
    format: "csv",
  }]
});

Database

The project supports 2 databases types: MongoDB and Local File Storage.

To use MongoDB, you need to install it:

npm install --save mongodb

The basic setup is simple:

KeyDescriptionType or OptionsRequired
typetype of database connectionmongo or customfalse
keya database key/identifyerstringfalse
namethe database namestringfalse

Custom Example

const server = new Server({
  // ...
  database: {
    type: "custom",
    key: "my-db",
    name: "database-name",
  }
});

Mongo Example

const server = new Server({
  // ...
  database: {
    type: "mongo",
    key: "my-db",
    name: "database-name",
    uri: "mongodb+srv://...",
  }
});

Multiple Databases Example

const server = new Server({
  // ...
  database: [{
    type: "custom",
    key: "my-db-1",
    name: "my-custom-db"
  }, {
    type: "mongo",
    key: "my-db-2",
    name: "my-mongo-db",
    uri: "mongodb+srv://...",
  }],
});

Entities

Entities are like models in a project. If you're creating a blog, this is the place where you should declare the Post, User, Comments, Likes, Tags, and other entities.

KeyDescriptionType or OptionsRequired
nameentity namestringtrue
aliasentity alias for visualization purposesstringtrue
fieldsobject with the entity fieldsobjecttrue
authauthentication settingsobjectfalse
permissionspublic access settingsobjectfalse

fields

The configuration is a key/value system, where the value should be the data type of the content, or a object with more settings.

The settings can look like this:

KeyDescriptionType or OptionsRequired
typetype of the contentstring, number, boolean, object, date, image, filetrue
requiredfield is a required for entitybooleanfalse
securefield should not be returned with responsesbooleanfalse

Check the below example:

const server = new Server({
  entities: [{
    name: "user",
    alias: "User",
    fields: {
      name: "string",
      email: {
        type: "string",
        required: true,
        secure: true
      }
    }
  }]
});

auth

The default value is false, so if you set this field in your entity, it means this is should be an authenticated entity.

KeyDescriptionType or OptionsRequired
fieldslist of the fields used for authenticationarraytrue
typeauthentication typejwt or tokenfalse
permissionsettings for access permissionobjectfalse

Check a complete example:

const server = new Server({
  entities: [{
    name: "user",
    alias: "User",
    fields: {
      name: "string",
      email: "string",
      password: "string",
    },
    auth: {
      type: "jwt",
      fields: ["login", "password"],
      permission: {
        "*": {
          insert: false,
          update: false,
          delete: false,
          list: true,
          get: true,
        },
        "post": {
          insert: true,
          update: true,
          delete: false,
          list: true,
          get: true,
        }
      }
    }
  }]
});

Custom Routes

You can easily add custom routes using the server object returned by the JSONServer Class, in a ExpressJS like manner.

const server = new Server({ ... });

server.routes.get("/my/endpoint", (req, res) => {
  res.json({ message: "It's working "})
})

Roadmap

Present features:

  • CRUD routes
    • Insert
    • List/Get
    • Update
    • Delete
    • Bulk insert
  • Authentication
    • JWT
    • Simple Token
    • Authentication routes
    • Authorization handler
  • Create tests for features
  • Interceptor to add custom requests
  • Add logger for request and API transactions
  • Full search for all entities
  • Finish Docs
  • Create Autogenerated Documentation for API Endpoints
  • File upload
  • Databases
    • In-Memory DB
    • PostgreSQL
    • MongoDB
    • MySQL

Future features:

  • Blog setup (?)
  • Chat setup (?)
  • Ecommerce Setup (?)
  • Bulk actions
    • Bulk insert
    • Bulk update
    • Bulk delete
2.0.3

2 years ago

2.0.2

2 years ago

2.0.5

2 years ago

2.0.4

2 years ago

2.0.7

2 years ago

2.0.6

2 years ago

2.0.9

2 years ago

2.0.8

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.9.10

2 years ago

1.9.9

2 years ago

0.0.10

3 years ago

0.0.11

3 years ago

0.0.12

3 years ago

0.0.13

3 years ago

0.0.14

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.5

3 years ago

0.0.6

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago