Konjection
by Alex Merced
Konjection is an abstraction and helper library for working Knex Query Build and the Objection ORM.
Konject
If all starts with the Konjection function. It takes a config object and in that config object there is a property called 'knex' which should have the configurations for your database connection to pass to Knex. It will return the Db object (Knex Object), Model object (Objection Model Object with the Knex Object in it), and konModel function (Function for creating model with crud functions for a table). Make sure the appropriate database drivers are installed for you project.
const konject = const config = knex: client: "pg" connection: host: "localhost" port: "5432" user: "test5" password: "test5" database: "test5" log: { console; } { console; } { console; } { console; } const DB Model konModel =
konModel function
Takes a string that is the name of the table in your database and returns the model with the following starter functions, you can always add more.
Item.all() => return all items
Item.one(id) => return one item based on ID
Item.create(newItem) => takes in an object and creates a new record
Item.update(id, updatedIem) => takes an ID and updates it based on the updatedItem
Item.destroy(id) => destroys the particular record
Item.related(id, relationship) => pull the data from a particular relationship
Item.relate(sourceID, targetID, relationship) => make an item from source model relate to target item in related model
In the below code we use the konModel function and add a special function for non-id based queries.
relationships
You can pass in a second object as an argument, keys in this object include.
relationships: function that returns object with relationship mapping
const konject = ; try // CONFIG OBJECT WITH KNEX CONNECTION INFO const config = knex: client: "pg" connection: host: "localhost" port: "5432" user: "test5" password: "test5" database: "test5" log: { console; } { console; } { console; } { console; } ; //RUNNING konject const DB Model konModel maker = ; // Create Models, Pet model has a belongs to relationship with owner const Owner = ; const Pet = ; //Executing database commands in async function const stuff = async { //Create Owners Table await maker; //Create Pets table await maker; //Create Some Owners and Pets await Owner; await Owner; await Owner; await Pet; await Pet; await Pet; //Grab pet with id one and log it const pet = await Pet; console; //Relate pet with id 1 with owner with id 1 await Pet; //Log the owner related to pet 1 console; //log all pets console; //log all pets, populate owner data console; }; ; catch error console;