Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

calustra-router

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

calustra-router

Expose database as API through koa-router

  • 0.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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.

Keywords

FAQs

Package last updated on 28 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc