endersoncosta / herbs2knex

Other
0 stars 2 forks source link

herbs2knex

herbs2knex creates postgresql repositories based on herbs entities (gotu)

Installing

$ npm install herbs2knex

Using

const { Repository } = require('herbs2knex')

class ItemRepository extends Repository {
    constructor() {
        super({
            entity: anEntity,
            table: 'aTable',
            ids: ['id'],
            dbConfig
        })
    }
}

const itemRepo = new ItemRepository()
const ret = await itemRepo.findByID(1)

Repository config:

entity - A Herbs entity reference

table - A Postgres table name

ids - The primary keys of the table

dbConfig - A object with database configuration

Repository vs ORM

The idea is to create a repositories with common methods needed for an application.

It is not the intention of this lib to create a ORM. For more complex scenarios it is recommended to extend the repository by use raw queries (just be careful with sql injection) or use favorite ORM, encapsulating inside a method the necessary queries or database operations.

For instance:

class ItemRepository extends Repository {
    constructor() {
        super({
            entity: anEntity,
            table: 'aTable',
            ids: ['id'],
            dbConfig
        })
    }

    getExcludedItemFromLastWeek() {
        ...
    }
}

const itemRepo = new ItemRepository()
const ret = await itemRepo.getExcludedItemFromLastWeek()

Retrieving and Persisting Data

findByID

Find by ID

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.findByID(10)

findBy

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.findBy({ stringTest: ["marie"] })

persist

An upsert.

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.persist(aModifiedInstance);

update

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.update(aModifiedInstance);

delete

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.delete(aModifiedInstance);

insert

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.insert(aModifiedInstance);

where

A knex implementation to that repository / table

const itemRepo = new ItemRepository(injection)
const ret = await itemRepo.where({ stringTest: "marie" })
const ret = await itemRepo.where({ stringTest: "marie" }, { first: true })

TODO

Features:

Retrieving and Persist: