Gathering detailed insights and metrics for node-pg-crud
Gathering detailed insights and metrics for node-pg-crud
Gathering detailed insights and metrics for node-pg-crud
Gathering detailed insights and metrics for node-pg-crud
Lightweight easy-to-use PostgreSQL CRUD handlers + utilities.
npm install node-pg-crud
Typescript
Module System
Node Version
NPM Version
TypeScript (72.16%)
JavaScript (27.19%)
Shell (0.65%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Apache-2.0 License
2 Stars
78 Commits
2 Watchers
2 Branches
1 Contributors
Updated on Feb 17, 2021
Latest Version
1.1.1
Package Id
node-pg-crud@1.1.1
Unpacked Size
61.35 kB
Size
15.27 kB
File Count
15
NPM Version
6.14.10
Node Version
12.20.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
Lightweight easy-to-use PostgreSQL CRUD handlers + utilities built. node-postgres is required.
1$ npm install node-pg-crud
1const CRUDBuilder = require('node-pg-crud')
The CRUDBuilder
object exposes a builder method to create a PostgreSQL Model, CRUDModel
to be used to call typical
CRUD Methods (get
, getById
, getByQuery
, insert
, put
, delete
).
Sets the default limit for the number of results when the CRUDModel.get()
method is called.
Returns CRUDModel
Type.
1const CRUDModel = new CRUDBuilder( 2 POOL, // Pool or Client instance from 'pg' library 3 MODEL_NAME, // Name of CRUDModel instance (typically the name of the table) 4 TABLE_NAME, // Name of table in PostgreSQL database 5 DEFAULT_SELECT_QUERY, // Default query to be used when querying data if no custom query is specified 6 DEFAULT_SELECT_WHERE_QUERY, // Default filter to be used when querying data if no custom where clause is specified 7 TABLE_KEY // Optional key to set when aliasing main referenced table, eg. 'select * from users u' where 'u' is the table key 8).build()
Returns Promise for a dataset matching the query requested with the following result structure.
1{ 2 total, // total amount of results for specific query 3 page, // current page 4 pageSize, // max number of items to be returned in data; can be 'all' or a number 5 results, // number of items returned in data 6 pages, // amount of pages given query 7 data: [ // results 8 {id: ..., ...}, 9 {}, 10 ... 11 ] 12}
The search parameter(s).
A custom search query which is passed directly to the database.
Search filter options to be combined with the other filter options, and the search query where applicable.
1{ status: 'active', enabled: true }
The requested page.
The different attributes which can be used to sort the results.
1{ id: 'asc', first_name: 'desc' }
Field names used to define what the search value is used to search through.
Used to define what is being queried and to also define the structure with which the data is returned for the result's objects.
Returns Promise for a single object returned from the database.
Object ID being referenced.
Used to define what is being queried and to also define the structure with which the data is returned for the result's objects.
Used to define a custom where
clause.
Returns Promise for a single or all matching objects from the table based on a constructed query.
Used to define the keys and variables being used to query.
1[{key: 'name', value: nameVariable}, {status: true, value: statusVariable}]
Used to define what is being queried and to also define the structure with which the data is returned for the result's objects.
Used to define whether the data returned is a single option or multiple.
Returns Promise for the object that was inserted.
Defines the structure with which the data is inserted.
Defines the values for the object to be inserted.
Returns Promise for the updated object.
Object ID being referenced.
Defines the query text for the data being updated.
Defines the values for the object to be updated.
Returns Promise for the updated object.
Object ID being referenced.
Defines the query text for the data being removed.
Defines the values for the object to be removed.
1const CRUDBuilder = require('node-pg-crud').default 2const { buildValuesEntries, buildUpdateEntries } = require('node-pg-crud') 3 4const TABLES = require('../tables') 5const { pool } = require('../../loaders/postgresql') 6 7const MODEL_NAME = 'User' 8const TABLE_NAME = TABLES.USERS 9const TABLE_KEY = 'u' 10 11const DEFAULT_SELECT_QUERY = ` 12${TABLE_KEY}.id, 13${TABLE_KEY}.first_name, 14${TABLE_KEY}.last_name, 15${TABLE_KEY}.email 16from ${TABLE_NAME} ${TABLE_KEY} 17` 18const DEFAULT_SELECT_WHERE_QUERY = `where ${TABLE_KEY}.id = $1 limit 1` 19 20// create instance of PG CRUD Model 21const CRUD = new CRUDBuilder(pool, MODEL_NAME, TABLE_NAME, DEFAULT_SELECT_QUERY, DEFAULT_SELECT_WHERE_QUERY, TABLE_KEY).build() 22 23const get = (query = {}, pagination = {}) => { 24 // use search & filter to create WHERE clause; search to do a text search across multiple columns, filter expects a where clause on a particular column 25 const searchFields = [ // single and concatenated columns to search through with search parameter 26 `${TABLE_KEY}.first_name || ' ' || ${TABLE_KEY}.last_name`, 27 `${TABLE_KEY}.email` 28 ] 29 return CRUD.get(query, pagination, searchFields, DEFAULT_SELECT_QUERY) 30} 31 32const getById = id => CRUD.getById(id, DEFAULT_SELECT_QUERY, DEFAULT_SELECT_WHERE_QUERY) 33 34const insert = ({ first_name, last_name, email }) => { 35 const values = [first_name, last_name, email] 36 const valuesText = buildValuesEntries(values) 37 const queryText = `insert into ${TABLE_NAME} (first_name, last_name, email) VALUES (${valuesText}) returning id` 38 39 return CRUD.insert(queryText, values) 40} 41 42const update = async (id, { first_name, last_name, email }) => { 43 const updateParams = { 44 first_name, 45 last_name, 46 email 47 } 48 49 const { updateSetQueryText, updateValues } = buildUpdateEntries(updateParams) 50 if (!updateSetQueryText) throw Error({ 51 id: `${MODEL_NAME.toLowerCase()}.update.error.no.input`, 52 message: `Failed to update ${MODEL_NAME}. No update values found.`, 53 }) 54 55 const values = [id, ...updateValues] 56 const queryText = `update ${TABLE_NAME} ${updateSetQueryText} where id = $1` 57 58 return CRUD.update(id, queryText, values) 59} 60 61const remove = id => { 62 const values = [id] 63 const queryText = `delete from ${TABLE_NAME} where id = $1` 64 65 return CRUD.remove(id, queryText, values) 66} 67 68module.exports = { 69 get, 70 getById, 71 insert, 72 update, 73 remove 74}
1const express = require('express') 2const httpStatus = require('http-status-codes') 3const { UserModel } = require('../../models') 4const { validate, validateRules } = require('./validator') 5 6const router = express.Router() 7 8router.get('/', validateRules('getUsers'), validate, async (req, res) => { 9 const {search, filter} = req.query 10 const {page, limit, sort} = req.query 11 12 try { 13 const result = await UserModel.get({ search, filter }, { page, limit, sort }) 14 res.send(result) 15 } catch (error) { 16 // log error 17 return res.status(httpStatus.SERVICE_UNAVAILABLE).send({ error: error.message }) 18 } 19}) 20 21router.get('/:id', validateRules('getUserById'), validate, async (req, res) => { 22 const {id} = req.params 23 24 try { 25 const result = await UserModel.getById(id) 26 res.send(result) 27 } catch (error) { 28 // log error 29 return res.status(httpStatus.SERVICE_UNAVAILABLE).send({ error: error.message }) 30 } 31}) 32 33router.post('/', validateRules('createUser'), async (req, res) => { 34 const params = req.body 35 36 try { 37 const result = await UserModel.insert(params) 38 res.send(result) 39 } catch (error) { 40 // log error 41 return res.status(httpStatus.SERVICE_UNAVAILABLE).send({ error: error.message }) 42 } 43}) 44 45router.put('/:id', validateRules('updateUser'), async (req, res) => { 46 const { id } = req.params 47 const params = req.body 48 49 try { 50 const result = await UserModel.update(id, params) 51 res.send(result) 52 } catch (error) { 53 // log error 54 return res.status(httpStatus.SERVICE_UNAVAILABLE).send({ error: error.message }) 55 } 56}) 57 58router.delete('/:id', validateRules('deleteUser'), async (req, res) => { 59 const { id } = req.params 60 61 try { 62 const result = await UserModel.remove(id) 63 res.status(httpStatus.NO_CONTENT).send() 64 } catch (error) { 65 // log error 66 return res.status(httpStatus.SERVICE_UNAVAILABLE).send({ error: error.message }) 67 } 68}) 69 70module.exports = router
git clone https://github.com/howard-e/node-pg-crud.git
cd node-pg-crud
npm install
npm run build
cd example/scrips
./db-populate-local.sh
to populate a PostgreSQL Database. (This script assumes a PostgreSQL database is running
locally on PORT: 5432
, with the username: admin
, password: Passw0rd1
and a database called database
)cd ..
.env
file with the structure shown in the .env.example
file. POSTGRES_CONNECTION_STRING
MUST BE SET.npm install
npm start
4040
by default. This can be adjusted by overwriting
the PORT
variable in the .env
file.Because it's easy to use.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no SAST tool detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
35 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More