1 | # 🌹 @sharyn/db
|
2 |
|
3 | [![npm](https://img.shields.io/npm/v/@sharyn/db.svg)](https://www.npmjs.com/package/@sharyn/db)
|
4 |
|
5 | This package provides database utilities and configs.
|
6 |
|
7 | ## 🌹 Install
|
8 |
|
9 | ```bash
|
10 | yarn add @sharyn/db
|
11 | ```
|
12 |
|
13 | ## 🌹 Usage
|
14 |
|
15 | ### knex-config.js
|
16 |
|
17 | A `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
|
22 | import { knex } from '@sharyn/db'
|
23 |
|
24 | export 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
|
35 | import { createQuery } from '@sharyn/db'
|
36 |
|
37 | const query = createQuery('Note')
|
38 |
|
39 | export const createNote = input => query().insert(input)
|
40 |
|
41 | export const findNoteById = (userId, id) =>
|
42 | query(userId)
|
43 | .where({ id })
|
44 | .first()
|
45 | ```
|
46 |
|
47 | ### `createQuery` with a transaction
|
48 |
|
49 | You can pass a transaction to `createQuery` as the second parameter:
|
50 |
|
51 | ```js
|
52 | import { createQuery, knex } from '@sharyn/db'
|
53 |
|
54 | const tableAQuery = createQuery('tableA')
|
55 | const tableBQuery = createQuery('tableB')
|
56 |
|
57 | export 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 |
|
66 | Two 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 |
|
77 | They define your columns the following way:
|
78 |
|
79 | ```js
|
80 | const 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 |
|
92 | const userIdCol = t =>
|
93 | t
|
94 | .uuid('userId')
|
95 | .references(`${USER}.id`)
|
96 | .onUpdate('cascade')
|
97 | .onDelete('cascade')
|
98 | .notNullable()
|
99 | ```
|