Skip to content

Commit

Permalink
Add better logger (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
G4brym authored Aug 31, 2024
1 parent b91917e commit 172d8aa
Show file tree
Hide file tree
Showing 24 changed files with 417 additions and 281 deletions.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ traditional ORM.
`workers-qb` is not intended to provide ORM-like functionality, rather to make it easier to interact with the database
from code for direct SQL access using convenient wrapper methods.

Currently, 2 databases are supported:
Currently, 3 databases are supported:

- [Cloudflare D1](https://developers.cloudflare.com/d1/)
- [PostgreSQL (using node-postgres)](https://developers.cloudflare.com/workers/databases/connect-to-postgres/)
- [Cloudflare D1](https://workers-qb.massadas.com/databases/cloudflare-d1/)
- [Cloudflare Durable Objects](https://workers-qb.massadas.com/databases/cloudflare-do/)
- [PostgreSQL (using node-postgres)](https://workers-qb.massadas.com/databases/postgresql/)
- [Bring your own Database](https://workers-qb.massadas.com/databases/bring-your-own-database/)

## Features

Expand All @@ -22,11 +24,9 @@ Currently, 2 databases are supported:
- [x] [Type Checks for data read](https://workers-qb.massadas.com/type-check/)
- [x] [Create/drop tables](https://workers-qb.massadas.com/basic-queries/#dropping-and-creating-tables)
- [x] [Insert/Bulk Inserts/Update/Select/Delete/Join queries](https://workers-qb.massadas.com/basic-queries/)
- [x] [Modular selects](https://workers-qb.massadas.com/modular-selects/)
- [x] [On Conflict for Inserts and Updates](https://workers-qb.massadas.com/advanced-queries/onConflict/)
- [x] [Upsert](https://workers-qb.massadas.com/advanced-queries/upsert/)
- [x] [Support for Cloudflare Workers D1](https://workers-qb.massadas.com/databases/cloudflare-d1/)
- [x] [Support for Cloudflare Workers PostgreSQL (using node-postgres)](https://workers-qb.massadas.com/databases/postgresql/)
- [ ] Named parameters (waiting for full support in D1)

## Installation

Expand Down
4 changes: 2 additions & 2 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ nav:
- type-check.md
- basic-queries.md
- modular-selects.md
- utility-methods.md
- utilities.md
- Advanced Queries:
- advanced-queries/fields.md
- advanced-queries/join.md
Expand All @@ -52,7 +52,7 @@ nav:
- advanced-queries/raw-sql.md
- Supported Databases:
- databases/cloudflare-d1.md
- databases/cloudflare-do-srs.md
- databases/cloudflare-do.md
- databases/postgresql.md
- databases/bring-your-own-database.md
markdown_extensions:
Expand Down
2 changes: 2 additions & 0 deletions docs/pages/databases/cloudflare-d1.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Cloudflare D1

## Create a database

```bash
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Cloudflare Durable Objects

## Write queries within your DO

```ts
Expand Down
2 changes: 2 additions & 0 deletions docs/pages/databases/postgresql.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# PostgreSQL

## Create a database

After creating your database, you must allow access from outside the private network, due to limitations on accessing
Expand Down
3 changes: 3 additions & 0 deletions docs/pages/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export default {
})
.execute()

// Or in a modular approach
const employeeList = await qb.select<Employee>('employees').where('active = ?', true).execute()

// You get IDE type hints on each employee data, like:
// employeeList.results[0].name

Expand Down
14 changes: 8 additions & 6 deletions docs/pages/index.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# workers-qb

### [Read the documentation here!](https://workers-qb.massadas.com/)

Zero dependencies Query Builder for [Cloudflare Workers](https://developers.cloudflare.com/workers/)

This module provides a simple standardized interface while keeping the benefits and speed of using raw queries over a
Expand All @@ -8,10 +10,12 @@ traditional ORM.
`workers-qb` is not intended to provide ORM-like functionality, rather to make it easier to interact with the database
from code for direct SQL access using convenient wrapper methods.

Currently, 2 databases are supported:
Currently, 3 databases are supported:

- [Cloudflare D1](https://developers.cloudflare.com/d1/)
- [PostgreSQL (using node-postgres)](https://developers.cloudflare.com/workers/databases/connect-to-postgres/)
- [Cloudflare D1](https://workers-qb.massadas.com/databases/cloudflare-d1/)
- [Cloudflare Durable Objects](https://workers-qb.massadas.com/databases/cloudflare-do/)
- [PostgreSQL (using node-postgres)](https://workers-qb.massadas.com/databases/postgresql/)
- [Bring your own Database](https://workers-qb.massadas.com/databases/bring-your-own-database/)

## Features

Expand All @@ -20,8 +24,6 @@ Currently, 2 databases are supported:
- [x] [Type Checks for data read](https://workers-qb.massadas.com/type-check/)
- [x] [Create/drop tables](https://workers-qb.massadas.com/basic-queries/#dropping-and-creating-tables)
- [x] [Insert/Bulk Inserts/Update/Select/Delete/Join queries](https://workers-qb.massadas.com/basic-queries/)
- [x] [Modular selects](https://workers-qb.massadas.com/modular-selects/)
- [x] [On Conflict for Inserts and Updates](https://workers-qb.massadas.com/advanced-queries/onConflict/)
- [x] [Upsert](https://workers-qb.massadas.com/advanced-queries/upsert/)
- [x] [Support for Cloudflare Workers D1](https://workers-qb.massadas.com/databases/cloudflare-d1/)
- [x] [Support for Cloudflare Workers PostgreSQL (using node-postgres)](https://workers-qb.massadas.com/databases/postgresql/)
- [ ] Named parameters (waiting for full support in D1)
75 changes: 75 additions & 0 deletions docs/pages/utilities.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
## .count()

On selects, you have the option to `.count()` the rows without having to build a new query everytime.

```ts
import { OrderTypes } from 'workers-qb'
const qb = new D1QB(env.DB)

type EmployeeRoles = {
role: string
count: number
}

async function listEmployees(page = 0) {
const qs = qb.fetchAll<EmployeeRoles>({
tableName: 'employees',
limit: 20,
offset: page * 20,
})

const thisPageEmployees = await qs.execute()
const employeeCount = await qs.count()

return {
employees: thisPageEmployees.results,
total: employeeCount.results.total,
}
}
```

## Logger

To enable simple `console.log(...)` with the query and execution duration

```ts
const qb = new D1QB(env.DB)
qb.setDebugger(true) // This call will define the default logger

await qb
.fetchAll<EmployeeRoles>({
tableName: 'employees',
fields: ['id', 'name'],
})
.execute()
```

Running the example above will print into the console this:

```
[workers-qb][34ms] {"query": "SELECT id, name FROM employees"}
```

### Advanced Logger

You can overwrite the default `console.log()` by passing a parameter to the query builder initializer

```ts
import { RawQuery, QueryLoggerMeta } from 'workers-qb'

const qb = new D1QB(env.DB, {
logger: async (query: RawQuery, meta: QueryLoggerMeta) => {
// run your own logic
// query timmings available in meta.duration in milliseconds
},
})

await qb
.fetchAll<EmployeeRoles>({
tableName: 'employees',
fields: ['id', 'name'],
})
.execute()
```

With this, your function will always be called after the query is executed, even if the query throws an error.
27 changes: 0 additions & 27 deletions docs/pages/utility-methods.md

This file was deleted.

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "workers-qb",
"version": "1.4.3",
"version": "1.5.0",
"description": "Zero dependencies Query Builder for Cloudflare Workers",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
Expand Down
40 changes: 38 additions & 2 deletions src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
InsertWithoutReturning,
Join,
OneResult,
QueryBuilderOptions,
QueryLoggerMeta,
RawQuery,
RawQueryFetchAll,
RawQueryFetchOne,
Expand All @@ -28,10 +30,44 @@ import { Query, QueryWithExtra, Raw } from './tools'
import { SelectBuilder } from './modularBuilder'

export class QueryBuilder<GenericResultWrapper> {
_debugger = false
protected options: QueryBuilderOptions

constructor(options?: QueryBuilderOptions) {
this.options = options || {}
}

setDebugger(state: boolean): void {
this._debugger = state
if (state === true) {
if (this.options.logger) {
// a logger already exists, so it shouldn't be overwritten
return
}

this.options.logger = (query: RawQuery, meta: QueryLoggerMeta) => {
console.log(`[workers-qb][${meta.duration}ms] ${JSON.stringify(query)}`)
}
} else {
this.options.logger = undefined
}
}

async loggerWrapper(query: Query | Query[], innerFunction: () => any) {
const start = Date.now()
try {
return await innerFunction()
} catch (e) {
throw e
} finally {
if (this.options.logger) {
if (Array.isArray(query)) {
for (const q of query) {
await this.options.logger(q.toObject(), { duration: Date.now() - start })
}
} else {
await this.options.logger(query.toObject(), { duration: Date.now() - start })
}
}
}
}

async execute(query: Query): Promise<any> {
Expand Down
Loading

0 comments on commit 172d8aa

Please sign in to comment.