@sharyn/db

    1.3.0 • Public • Published

    🌹 @sharyn/db

    npm

    This package provides database utilities and configs.

    🌹 Install

    yarn add @sharyn/db

    🌹 Usage

    knex-config.js

    A knex-config.js knexfile is provided and is used automatically unless you have your own located at src/_db/knex-config.js

    knex

    import { knex } from '@sharyn/db'
     
    export const findNoteById = (userId, id) =>
      knex('Note')
        .where({ id, userId })
        .first()

    createQuery

    createQuery is higher-level than knex, the created query already contains the table name, and can pass a userId as a .where({ userId }) clause.

    import { createQuery } from '@sharyn/db'
     
    const query = createQuery('Note')
     
    export const createNote = input => query().insert(input)
     
    export const findNoteById = (userId, id) =>
      query(userId)
        .where({ id })
        .first()

    createQuery with a transaction

    You can pass a transaction to createQuery as the second parameter:

    import { createQuery, knex } from '@sharyn/db'
     
    const tableAQuery = createQuery('tableA')
    const tableBQuery = createQuery('tableB')
     
    export const somethingWithATransaction = userId =>
      knex.transaction(async trx => {
        await tableAQuery(userId, trx).something()
        await tableBQuery(null, trx).something()
      })

    Migration helpers

    Two helpers are available to reduce bloat in your migration files, standardCols and userIdCol:

      up: async knex => {
        await knex.schema.createTable('Note', t => {
        standardCols(knex, t)
        userIdCol(t)
        })
      }

    They define your columns the following way:

    const standardCols = (knex: Function, t: Object) => {
      t.uuid('id').primary()
      t
        .timestamp('createdAt')
        .notNullable()
        .defaultTo(knex.fn.now())
      t
        .timestamp('updatedAt')
        .notNullable()
        .defaultTo(knex.fn.now())
    }
     
    const userIdCol = (t: Object) =>
      t
        .uuid('userId')
        .references(`${USER}.id`)
        .onUpdate('cascade')
        .onDelete('cascade')
        .notNullable()

    Keywords

    none

    Install

    npm i @sharyn/[email protected]

    Version

    1.3.0

    License

    MIT

    Unpacked Size

    4.17 kB

    Total Files

    9

    Last publish

    Collaborators

    • avatar