npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

calustra-router

v0.3.0

Published

Expose database as API through koa-router

Downloads

54

Readme

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.