Typescript high level class to typesafe your database query, requiring knex as middle-layer query-builder. Type-check your column name, column type, column attributes. Distinguish different db operations input:
select
,update
,delete
(where db generated columns likeid
,created_at
exist)insert
(whereid
is not there yet)
This package is written in Typescipt and utilize Typescript to type-check table/model and column/property. Although it's compiled into Javascript but there's no use in using pure Javascript, since its core purpose is to type-safe database queries.
npm i safedb --save
or
yarn add safedb
Your database declaration file. Here you will use the classFactory
to inject db instance into Base
class.
Then export it to be used later with your models.
import * as Knex from 'knex';
import { classFactory } from './baseClassFactory';
// example config
const db = Knex({
client: 'pg',
connection: process.env.DATABASE_URL,
pool: {
min: 0,
max: 1,
},
asyncStackTraces: true, // this line will safe you a whole lot of time
});
const Base = classFactory(db);
export Base;
Model declaration. This might look verbose and cumbersome, but you'll end up declare a model sooner or later, under the form of type
, interface
, or class
if you're using Typescipt.
Just extends
your Model from Base
class. It will ensure you to put in your tableName
.
import { Base } from './db';
class User extends Base {
tableName: 'users';
public name: string;
public address: string;
public age: number;
}
Just instantiate a model instance when you need to use it:
const user = new User();
user.find({})
There will be circumstances where you need a query-builder, just call queryBuilder()
method.
Available methods:
find
findOne
findByIds
findAll
insert
update
delete