|
| 1 | +## .count() |
| 2 | + |
| 3 | +On selects, you have the option to `.count()` the rows without having to build a new query everytime. |
| 4 | + |
| 5 | +```ts |
| 6 | +import { OrderTypes } from 'workers-qb' |
| 7 | +const qb = new D1QB(env.DB) |
| 8 | + |
| 9 | +type EmployeeRoles = { |
| 10 | + role: string |
| 11 | + count: number |
| 12 | +} |
| 13 | + |
| 14 | +async function listEmployees(page = 0) { |
| 15 | + const qs = qb.fetchAll<EmployeeRoles>({ |
| 16 | + tableName: 'employees', |
| 17 | + limit: 20, |
| 18 | + offset: page * 20, |
| 19 | + }) |
| 20 | + |
| 21 | + const thisPageEmployees = await qs.execute() |
| 22 | + const employeeCount = await qs.count() |
| 23 | + |
| 24 | + return { |
| 25 | + employees: thisPageEmployees.results, |
| 26 | + total: employeeCount.results.total, |
| 27 | + } |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +## Logger |
| 32 | + |
| 33 | +To enable simple `console.log(...)` with the query and execution duration |
| 34 | + |
| 35 | +```ts |
| 36 | +const qb = new D1QB(env.DB) |
| 37 | +qb.setDebugger(true) // This call will define the default logger |
| 38 | + |
| 39 | +await qb |
| 40 | + .fetchAll<EmployeeRoles>({ |
| 41 | + tableName: 'employees', |
| 42 | + fields: ['id', 'name'], |
| 43 | + }) |
| 44 | + .execute() |
| 45 | +``` |
| 46 | + |
| 47 | +Running the example above will print into the console this: |
| 48 | + |
| 49 | +``` |
| 50 | +[workers-qb][34ms] {"query": "SELECT id, name FROM employees"} |
| 51 | +``` |
| 52 | + |
| 53 | +### Advanced Logger |
| 54 | + |
| 55 | +You can overwrite the default `console.log()` by passing a parameter to the query builder initializer |
| 56 | + |
| 57 | +```ts |
| 58 | +import { RawQuery, QueryLoggerMeta } from 'workers-qb' |
| 59 | + |
| 60 | +const qb = new D1QB(env.DB, { |
| 61 | + logger: async (query: RawQuery, meta: QueryLoggerMeta) => { |
| 62 | + // run your own logic |
| 63 | + // query timmings available in meta.duration in milliseconds |
| 64 | + }, |
| 65 | +}) |
| 66 | + |
| 67 | +await qb |
| 68 | + .fetchAll<EmployeeRoles>({ |
| 69 | + tableName: 'employees', |
| 70 | + fields: ['id', 'name'], |
| 71 | + }) |
| 72 | + .execute() |
| 73 | +``` |
| 74 | + |
| 75 | +With this, your function will always be called after the query is executed, even if the query throws an error. |
0 commit comments