Getting started

Installing Gybson

Gybson has a peer dependency on relational-schema and Knex.

npm i gybson relational-schema knex

Generating the client

About code gen

Gybson generates Typescript code from your database schema.

It uses the relational-schema library as a peer dependency to generate a schema file from your database.

important

We never recommend running the code gen against your production database. Instead you should run it against a local database with the same schema.

Configuring code gen

First introspect your database using relations introspect. You can find the full docs here (Note that only the CommonJS output format is currently supported).

Define a config file gybson.json in the root directory of your project.

The schemaFile option specifies the relative path the the schema file generated by relational-schema.

The outdir option specifies where the client code files will be output. This should be inside of your project source so that the files are transpiled as part of your build.

You can optionally specify:

prettierConfig - a path to a prettier config to apply to generated code

example config:

{
"schemaFile": "src/lib/database/relational-schema.ts",
"outdir": "src/lib/database/",
"prettierConfig": "prettierrc.js"
}

Run:

gybson generate

Using the client

Gybson wraps a Knex instance.

import { knex } from 'knex';
import { GybsonClient } from '...my-outdir...';
const knexClient = knex({ ... });
const gybson = new GybsonClient(knexClient);

You can also pass options for:

logLevel - debug, info, warn, error. logger - a custom logger to use instead.

const logger = new MyLogger();
const gybson = new GybsonClient(knexClient, { logger });

Querying

tip

We recommend creating a client on a per-request basis for stateless APIs i.e. GraphQL, REST. This will ensure the cache is clean and no stale data is returned. See DataLoader for more details

import { GybsonClient } from '...my-outdir...';
...
const client = new GybsonClient(knexInstance);
const id = await gybson.user.insert({
values: {
...
},
});

You can also import individual table clients like:

import { UserClient } from '...my-outdir...';
const userClient = new UserClient({ ... });
const user = await userClient.loadOne({ ... });

For a full list of query options see Querying

Closing the connection

To close the connection pool, you can either destroy the knex instance or call:

gybson._close();