0.3.0 • Published 1 year ago

calustra-router v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Calustra logo

NPM Version NPM Downloads

Intro

calustra-router adds a koa-router Router to your Koa app exposing a CRUD API with endpoints for your database tables.

This API will consist on two kind of endpoint / methods:

  • crud · GET methods: read, key_list, distinct, find . POSTmethods: save, update, delete

  • queries: custom defined endpoints pointing to custom methods

Currently, supported databases are:

  • PostgreSQL
  • SQLite

Check calustra-conn for more info.

Install

npm install calustra-router [--save-dev]

Get started

Here a simple server serving calustra-router API on /api path:

import Koa from 'koa'
import {initCalustraRouter} from 'calustra-router'

const connConfig= {
  connection: {
    database: {
      host:     'localhost',
      port:      5432,
      database: 'calustra-orm',
      user:     'postgres',
      password: 'postgres'
    },
    options: {
      log: 'info',
    },
  },
  tables: ['screw_stock']
}

const routesConfig= {
  // router options
  crud: {
    prefix: '/api',
    routes: ['screw_stock'],
  }   
}

const app = new Koa()

initCalustraRouter(app, connConfig, routesConfig)

const server= app.listen(3000, function () {
  console.log('Server is listening...')
})

Given previous server, API could be consumed like this:

import fetch from 'node-fetch'

const url= `http://localhost:3000/api/screw_stock/read`
const response= await fetch(url)
let screw_data= await response.json()

API

calustra-router has these use-approach (somehow Koa style) methods:

But each piece is also exposed:

initCalustraDbContext(app, connOrConfig)

  • app is your Koa app.
  • connOrConfig is used to initialize the database connection (or read a cached one). Check calustra-orm

This methods extends the app.context with this:

  app.context.db= {
    getConnection,
    getModel
  }

initCalustraRouter(app, connOrConfig, routes)

  • app is your Koa app.
  • connOrConfig is used to initialize the database connection (or read a cached one). Check calustra-orm
  • routes

This methods creates a calustraRouter and attaches it to your app.

calustraRouter(connOrConfig, routes)

  • connOrConfig is used to initialize the database connection (or read a cached one). Check calustra-orm
  • routes

Creates a koa-router Router, and attached to it a series of endpoints depending on your routes.

routes config

Is an object like this:

{
  crud: {... crud config ...},
  queries: {...queries config...},
  {...custom options...}
}

Custom options schema, bodyField, getUserId and authUser can be specified at any scope. For example:

{
  getUserId: (ctx) => { return -1 }
  crud: {
    prefix: '/api',
    getUserId: (ctx) => { return 0 }
    routes: [
      {
        name: 'screw_stock',
        getUserId: (ctx) => { return 1 }
      }
    ]
  }
}

routes.crud

  {
    prefix: '/crud,
    routes: 
      // Can be:
      '*' // => autodetect and create routes for every table on the database
      // or
      // an array of tables config, where each config can be:
      // - a simple string with the table name
      // - an object like this:
        {
          name: "table_name",
          schema: "public", // optional
          url: "custom/url",

          options: {

            mode: 'r', // 'r' / 'rw' / 'ru' (read+update but not delete) / 'w' / 'u'

            useUserFields: {
              use: false,
              fieldNames: {
                created_by: 'created_by', 
                last_update_by: 'last_update_by'
              },
            },

            getUserId: (ctx) => {
              let uid= ctx.headers['user-id']
              if (uid!=undefined) {
                return uid
              }
              return undefined
            },

            authUser: {
              require: false,     // true / false / 'read-only'
              action: 'redirect', // 'error'
              redirect_url: '/',
              error_code: 401
            }
          }
        }      
  } 
  

routes.queries

  {
    prefix: '/queries',
    routes: [
      // List of objects like
      {
        url: '/screw_stock/fake',
        method: 'POST',
        callback: (ctx) => {},
        authUser: {
          require: true,
          action: 'redirect',
          redirect_url: '/'
        },  
      }
    ]
  }

routes.schema

By default is is public. Specifies which database's schema to work with.

routes.bodyField

By default it is undefined, which means that queries callbacks will return data on the ctx.body directly. If you pass son value, for example result, then data will be:

// ctx.body
{
  result: {...thedata}
}

routes.getUserId

A callback receiving one param ctx and returning the logged in user id -if any-.

  {
    getUserId: (ctx) => {
      let uid= ctx.headers['user-id']
      if (uid!=undefined) {
        return uid
      }
      return undefined
    }
  }

options.authUser

  {
    authUser: {
      require: false,     // true / false / 'read-only'
      action: 'redirect', // 'error'
      redirect_url: '/',
      error_code: 401
    }
  }

async initCalustraRouterForAllTables(app, connOrConfig, schema= 'public')

  • app is your Koa app.
  • connOrConfig is used to initialize the database connection (or read a cached one). Check calustra-orm

This methods creates a calustraRouterForAllTables and attaches it to your app.

async calustraRouterForAllTables(connOrConfig, prefix= '', schema= 'public')

  • connOrConfig is used to initialize the database connection (or read a cached one). Check calustra-orm

Creates a koa-router Router, and attached to it crud routes for every table in the database.

0.3.0

1 year ago

0.2.7

1 year ago

0.2.6

1 year ago

0.2.8

1 year ago

0.2.5

1 year ago

0.2.4

1 year ago

0.1.0

1 year ago

0.2.1

1 year ago

0.1.2

1 year ago

0.2.0

1 year ago

0.1.1

1 year ago

0.2.3

1 year ago

0.1.4

1 year ago

0.2.2

1 year ago

0.1.3

1 year ago

0.1.5

1 year ago

0.0.37

2 years ago

0.0.36

2 years ago

0.0.20

2 years ago

0.0.21

2 years ago

0.0.22

2 years ago

0.0.23

2 years ago

0.0.24

2 years ago

0.0.25

2 years ago

0.0.30

2 years ago

0.0.31

2 years ago

0.0.32

2 years ago

0.0.33

2 years ago

0.0.34

2 years ago

0.0.35

2 years ago

0.0.26

2 years ago

0.0.27

2 years ago

0.0.28

2 years ago

0.0.29

2 years ago

0.0.19

2 years ago

0.0.18

2 years ago

0.0.17

2 years ago

0.0.16

2 years ago

0.0.15

2 years ago

0.0.14

2 years ago

0.0.13

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago