pg-models

1.0.7 • Public • Published

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

PgormModel

Constants

globalOptions
modalOptions

All globalOptions plus option to change table name

columnsObj

define columns according to following object structure

Functions

validatorFn(val, col, values)

Validation function for user input validation

PgormModel

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

new PgormModel(modalName, options)

Creates new modal and relevant table

Param Type Description
modalName string The name of the modal and table
options modalOptions Modal 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

Param Type Description
columns columnsObj Table columns with configurations
options object Options 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

Param Type Description
options Object Options 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

Param Type Description
whereClause String SQL query starting with 'WHERE'
paramsArray Array Array 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

Param Type Description
column String Name of the column to search
value String Value 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

Param Type Description
id Number Id 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

Param Type Description
id Number Id of the record to be updated
values Object New 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

Param Type Description
values Object Values 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

Param Type Description
id Number Id 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

Param Type Description
fn function A 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

Param Type Description
fn function A 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

Param Type Description
fn function A 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

Param Type Description
methodName String The name for the function
fn function A 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

Param Type Description
fkName String Name of the foreign key
parentTableName String The 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

Param Type Description
dbConnection PG_Client The 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

Param Type Description
options globalOptions Configuration options.

globalOptions

Kind: global constant
Properties

Name Type Description
tablePrefix string Prefix for table name
tableSchema string Schema for table
pkName string Name of primary key of table
timestamps boolean | object Whether to add timestamps or not, provide object to override default values
paranoid boolean Whether to soft delete or not
alter boolean Whether to alter table (on config change) or not
errorLogs boolean Whether 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

Name Type Description
string tableName Name of table for current model

columnsObj

define columns according to following object structure

Kind: global constant
Properties

Name Type Description
columnName object Name of the column
schema string Schema of the column
validations Array Array 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

Param Type Description
val any Value entered for current column
col string Name of current column
values object All user entered values

Package Sidebar

Install

npm i pg-models

Weekly Downloads

0

Version

1.0.7

License

ISC

Unpacked Size

39.9 kB

Total Files

6

Last publish

Collaborators

  • abdullah-yasir