UNPKG

2.07 kBMarkdownView Raw
1# 🌹 @sharyn/db
2
3[![npm](https://img.shields.io/npm/v/@sharyn/db.svg)](https://www.npmjs.com/package/@sharyn/db)
4
5This package provides database utilities and configs.
6
7## 🌹 Install
8
9```bash
10yarn add @sharyn/db
11```
12
13## 🌹 Usage
14
15### knex-config.js
16
17A `knex-config.js` _knexfile_ is provided and is used automatically unless you have your own located at `src/_db/knex-config.js`
18
19### `knex`
20
21```js
22import { knex } from '@sharyn/db'
23
24export const findNoteById = (userId, id) =>
25 knex('Note')
26 .where({ id, userId })
27 .first()
28```
29
30### `createQuery`
31
32`createQuery` is higher-level than `knex`, the created query already contains the table name, and can pass a `userId` as a `.where({ userId })` clause.
33
34```js
35import { createQuery } from '@sharyn/db'
36
37const query = createQuery('Note')
38
39export const createNote = input => query().insert(input)
40
41export const findNoteById = (userId, id) =>
42 query(userId)
43 .where({ id })
44 .first()
45```
46
47### `createQuery` with a transaction
48
49You can pass a transaction to `createQuery` as the second parameter:
50
51```js
52import { createQuery, knex } from '@sharyn/db'
53
54const tableAQuery = createQuery('tableA')
55const tableBQuery = createQuery('tableB')
56
57export const somethingWithATransaction = userId =>
58 knex.transaction(async trx => {
59 await tableAQuery(userId, trx).something()
60 await tableBQuery(null, trx).something()
61 })
62```
63
64### Migration helpers
65
66Two helpers are available to reduce bloat in your migration files, `standardCols` and `userIdCol`:
67
68```js
69 up: async knex => {
70 await knex.schema.createTable('Note', t => {
71 standardCols(knex, t)
72 userIdCol(t)
73 })
74 }
75```
76
77They define your columns the following way:
78
79```js
80const standardCols = (knex, t) => {
81 t.uuid('id').primary()
82 t
83 .timestamp('createdAt')
84 .notNullable()
85 .defaultTo(knex.fn.now())
86 t
87 .timestamp('updatedAt')
88 .notNullable()
89 .defaultTo(knex.fn.now())
90}
91
92const userIdCol = t =>
93 t
94 .uuid('userId')
95 .references('User.id')
96 .onUpdate('cascade')
97 .onDelete('cascade')
98 .notNullable()
99```