Skip to content

getting started

kapil verma edited this page Jun 30, 2019 · 2 revisions

title: Getting Started

Getting Started

npm install --save tabel

In node.js projects one usually needs to prefix NODE_PATH=. in the command that executes the entry-file*. This is done in order to avoid writing things like require(../../../foo), (ie. Too many ../)when requiring top-level application modules. You can read more about this practice on this article from RisingStack blog.

(* entry-file is the script that you run to start your http server, or the script that is run while interacting with the app via cli)

The rest of this section will guide you through setting up tabel ORM in your node.js project which has a certain NODE_PATH set.

  • Create a folder named orm in code-root. Your code-root is whatever you set your NODE_PATH env variable to point to.
  • Create files named
    • orm/config.js
    • orm/tables.js
    • orm/index.js

config.js

Copy the following code into orm/config.js:

module.exports = {
  db: {
    client: 'postgresql',
    connection: {
      database: 'api_dev',
      host: 'localhost',
      port: 5432,
      user: 'dev',
      password: 'dev'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: 'knex_migrations'
  },
  // redis config is optional, is used for caching by tabel
  redis: {
    host: 'localhost',
    port: '6379',
    keyPrefix: 'dev.api.'
  }
};

tables.js

Copy the following code into orm/tables.js:

module.exports = (orm) => {
  // table definitions go over here.
};

This file is used for table definitions. You can read more about them here.


index.js

Copy the following code into orm/index.js:

const Tabel = require('tabel');
const config = require('./config');

const orm = new Tabel(config);

require('./tables')(orm);

module.exports = orm.exports;
/**
This is what the exports look like:

this.exports = {
  orm: this,
  table: this.table.bind(this),
  trx: this.trx.bind(this),
  raw: this.raw.bind(this),
  migrator: this.migrator,
  cache: this.cache,
  knex: this.knex,
  scoper: this.scoper,
  shape: this.shape
};
**/

Each property of orm.exports object is discussed in detail over here. With this sort of setup you can access the most used exports in a simple manner like shown below:

const {table, trx, raw} = require('orm');

return trx((t) => { // start a transaction
  return Promise.all([
    table('users', t).insert({username: 'foo'}),
    table('posts', t).upvotes().join().select('*', raw('count(upvotes.post_id) as upvotes')).all()
  ]);
}).then(([user, posts]) => {
  // do things on a successful transaction
}).catch(() => {
  // do things in case of an error, and transaction rollback
});

Next > Migrations

Clone this wiki locally