1.0.7 • Published 2 years ago

pg-models v1.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

PgormModel

ORM essentials for code written using default pg driver

Features

  • Ports easily with existing default pg-driver code
  • Built in basic CRUD methods
  • Creates models and relevant tables
  • Plain SQL schema for model columns
  • User input validation right in the model
  • Record validation hooks for create, update and delete operations
  • Enhance model functionaliy by adding custom query methods to it
  • Customize individual model behavior or of all instances
  • Linking to existing tables by adding foreight keys

Installation

PgormModel requires Node.js v14+ to run.

npm install --save pg-models

API Reference

Classes

Constants

Functions

PgormModel

Kind: global class
Summary: Installation: npm install pg-models
Version: v1.0.7

new PgormModel(modalName, options)

Creates new modal and relevant table

ParamTypeDescription
modalNamestringThe name of the modal and table
optionsmodalOptionsModal customization options

Example

const PgormModel = require('pg-models');

const Users = new PgormModel('users');

pgormModel.tableName

gets or sets the table name (with prefix)

Kind: instance property of PgormModel

pgormModel.define(columns, options)

Creates new table for the model with given configurations. Alters the table if already exists according to the given configurations.

Kind: instance method of PgormModel

ParamTypeDescription
columnscolumnsObjTable columns with configurations
optionsobjectOptions to modify the behaviour of PgormModel

Example

Users.define({
  fullname: {
    schema: 'fullname TEXT NOT NULL',
    validations: [
      function (input, colName) {
        if (typeof input !== "string") throw new Error(colName + ' must be a string')
      },
      function (input, colName) {
        if (input.length < 5) throw new Error(colName + ' can not be less than 5 char')
      },
    ]
  },
  age: {
    schema: 'age INT',
    validations: [
      function (input) {
        if (typeof input !== "number") throw new Error('age must be a number')
      }
    ]
  },
  about: {
    schema: 'about TEXT'
  },
});

pgormModel.findAll(options) ⇒

Gets all the results in the model

Kind: instance method of PgormModel
Returns: Array of results or an empty array

ParamTypeDescription
optionsObjectOptions to configure the query

Example

const users = await Users.findAll();

pgormModel.findAllWhere(whereClause, paramsArray) ⇒

Gets all the results in the model, matching whereClause

Kind: instance method of PgormModel
Returns: Array of results or an emtpy array

ParamTypeDescription
whereClauseStringSQL query starting with 'WHERE'
paramsArrayArrayArray of values for the query placeholders

Example

const users = await Users.findAllWhere('WHERE age>=$1', [20]);

pgormModel.findOne(column, value) ⇒

Gets the one matching result

Kind: instance method of PgormModel
Returns: Object or null

ParamTypeDescription
columnStringName of the column to search
valueStringValue for the column to match

Example

const user = await Users.findOne('fullname', 'Ali Hassan');

pgormModel.findById(id) ⇒

Gets the result from the model against the given id. Return null if no result found.

Kind: instance method of PgormModel
Returns: Object or null

ParamTypeDescription
idNumberId of the result

Example

const user = await Users.findById(12);

pgormModel.updateById(id, values) ⇒

Updates the record by given id

Kind: instance method of PgormModel
Returns: Updated record or null

ParamTypeDescription
idNumberId of the record to be updated
valuesObjectNew values for the record

Example

const updatedUser = await Users.updateById(12,{fullname: 'Ali Hussain', age: 23});

if(updatedUsers){
   // user updated do something with updatedUser...
} else {
   // user not found with that id...
}

pgormModel.create(values) ⇒

Creates new record

Kind: instance method of PgormModel
Returns: Created record or null

ParamTypeDescription
valuesObjectValues for the new record

Example

const user = await Users.create({fullname: 'Huzaifa Tayyab', age: 23});

pgormModel.deleteById(id) ⇒

Deletes the record by given id

Kind: instance method of PgormModel
Returns: boolean

ParamTypeDescription
idNumberId of the record to be deleted

Example

const isUserDeleted = await Users.deleteById(12);

if(isUserDeleted){
   // deleted
} else {
   // user not found with that id
}

pgormModel.beforeCreate(fn)

Registers a validator hook, which is called before every 'create' operation on this model. Validator function must throw error on validation failure.

Kind: instance method of PgormModel

ParamTypeDescription
fnfunctionA function to run before PgormModel.create(..) operation

Example

Users.beforeCreate(async (client, values)=>{
  // await client.query(..)
  // throws error on validation failure
})

pgormModel.beforeUpdate(fn)

Registers a validator hook, which is called before every 'update' operation on this model. Validator function must throw error on validation failure.

Kind: instance method of PgormModel

ParamTypeDescription
fnfunctionA function to run before PgormModel.update(..) operation

Example

Users.beforeUpdate(async (client, recordId)=>{
  // await client.query(..)
  // throws error on validation failure
})

pgormModel.beforeDestroy(fn)

Registers a validator hook, which is called before every 'delete' operation on this model. Validator function must throw error on validation failure.

Kind: instance method of PgormModel

ParamTypeDescription
fnfunctionA function to run before PgormModel.destory(..) operation

Example

Users.beforeDestroy(async (client, recordId)=>{
  // await client.query(..)
  // throws error on validation failure
})

pgormModel.addQueryMethod(methodName, fn)

Creates new function on the model, that can be accessed by the model instance. i.e MyModel.customQueries.myCustomQueryMethod(..)

Kind: instance method of PgormModel

ParamTypeDescription
methodNameStringThe name for the function
fnfunctionA callback which returns a query function to attach to the model,

Example

Users.addQueryMethod('getByQualification', (client)=>{
  // here you define and return your query function
  return async (qual_id) => {
    // const { rows: usersByQual } = await client.query(..)
    // return usersByQual
  }
});

// in users controller
await Users.customQueries.getByQualification(1)

pgormModel.addForeignKey(fkName, parentTableName)

Creates a foreign key. fkName must be present in the model Throws error if the foreign key already exists or column is not defined in the model.

Kind: instance method of PgormModel

ParamTypeDescription
fkNameStringName of the foreign key
parentTableNameStringThe name of the parent table to which key is being linked

Example

const Books = new PgormModel('books', {
  title: {
     schema: 'title VARCHAR(255)',
  },
  user_id: {
     schema: 'user_id INT',
  },
});

// create a foreign key on user_id column
Books.addForeignKey('user_id', Users.tableName);

PgormModel.useConnection(dbConnection)

Kind: static method of PgormModel

ParamTypeDescription
dbConnectionPG_ClientThe pg client object returned by pg.connect()

Example

PgormModel.useConnection(pgClient);

PgormModel.setOptions(options)

Sets options for PgormModel class that will apply to all instances of this class. Use this method if you want to customize all models once.

Kind: static method of PgormModel

ParamTypeDescription
optionsglobalOptionsConfiguration options.

globalOptions

Kind: global constant
Properties

NameTypeDescription
tablePrefixstringPrefix for table name
tableSchemastringSchema for table
pkNamestringName of primary key of table
timestampsboolean | objectWhether to add timestamps or not, provide object to override default values
paranoidbooleanWhether to soft delete or not
alterbooleanWhether to alter table (on config change) or not
errorLogsbooleanWhether to log errors or not

Example

// timestamps property can be boolean or object
timestamps: true
// or
timestamps: {
   createdAt: 'created_at',
   updatedAt: 'updated_at',
   deletedAt: 'deleted_at',
}

modalOptions

All globalOptions plus option to change table name

Kind: global constant
Properties

NameTypeDescription
stringtableNameName of table for current model

columnsObj

define columns according to following object structure

Kind: global constant
Properties

NameTypeDescription
columnNameobjectName of the column
schemastringSchema of the column
validationsArrayArray of validation functions

Example

const columnsObj = {
 columnName: {
   schema: 'columnName TEXT NOT NULL',
   validations: [validatorFn],
 },
 // ...other columns
};

validatorFn(val, col, values)

Validation function for user input validation

Kind: global function

ParamTypeDescription
valanyValue entered for current column
colstringName of current column
valuesobjectAll user entered values
1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago