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 | ```
|