Giter Club home page Giter Club logo

gatepost's Introduction

#Gatepost: Bind to Models From SQL

picture of fence with gate

npm i gatepost

Gatepost facilitates binding SQL statements to Model factories and instances, with the results cast as Model instance. With most ORMs have you model the database schema, but with Gatepost, you're not concerned with the database structure, only with what your queries return.

Gatepost uses VeryModel for Model factories and instances, giving you a lot of flexibility such as sharing your validation between your API and database, auto-converting values, etc.

Feel free to use knex, template strings, or other methods for generating your SQL. Gatepost is designed to stay out of your way.

'use strict';

const Gatepost = require('gatepost')('postgres://localhost/gatepost_test');
const SQL = require('sql-template-string'); //propery breaks out SQL template strings into a separate array to prevent SQL injection and errors

const Book = new Gatepost.Model({
  title: {
    validate: Joi.string()
  },
  id: {}
}, {
  cache: true,
  name: 'Book'
});

const knex = require('knex')({dialect: 'pg'});

//knex query builders are dealt with automatically
Book.fromSQL({
  name: 'getByCategory',
  sql: (args) => knex.select('id', 'title', 'author')
  .from('books').where({category: args.category})
});

Book.getByCategory({category: 'cheese'}).then(results) {
  results.forEach((book) => console.log(book.toJSON());
}).catch((err) => {
  console.log("error!!!!");
});
"use strict"

let SQL = require('sql-template-strings');
//sql-template-strings template tag returns a {text, values} object
//which gets turned into a prepare statement by gatepost

Book.fromSQL({
  name: 'insert',
  //using a template string
  sql: (args, model) => SQL`INSERT INTO books
(title, author, category)
VALUES (${model.title}, ${model.author}, ${model.category})
RETURNING id`,
  instance: true,
  oneResult: true
});

let book = Book.create({title: 'Ham and You', author: 'Nathan Fritz', category: 'ham'});

//using promises
book.insert()
.then((result) => console.log(`Book ID: ${book.id}`))
.catch((error) => console.log(`Gadzoons and error! ${error}`));

Model extensions

See VeryModel documentation for information on using gatepost.Models.

##Model options:

  • name: [string] used for naming the model
  • cache: [boolean] to refer to the model by string

Functions

fromSQL

Generate a Factory or Instance method from SQL for your Model

Arguments:

  • options: [object]

Options

  • name: [string] method name
  • sql: [function] returns the query object or string for pg.query or array of these.
  • oneResult: [boolean] only get one model intance or rejects with new gatepost.EmptyResult
  • instance: [boolean] Add the method to model instances rather than the factory.
  • model: [Model or string] cast the results into this model
  • validate: [Joi Schema] validate the args with this Joi Schema
  • validateOps: [object] Options passed to Joi.validate when validating arguments
  • validateModel: [boolean] True by default, instanced methods will validate the model (second arg) before running query.

Generated Method

function (args);

  • args: [object unless oneArg set] optional, the first argument passed to the sql function

returns Promise

Returned Promise

Calling a method generated from fromSQL returns a Promise which will then with the results, catch with a Postgres error from pg or gatepost.EmptyResult.

SQL Function

  • args: [object] arguments passed as the first option
  • model: [Model] for instances, the model instance that the function is called to

Examples

let knex = require('knex')({dialect: 'pg'});

//knex query builders are dealt with automatically
Book.fromSQL({
  name: 'getByCategory',
  sql: (args) => knex.select('id', 'title', 'author')
  .from('books').where({category: args.category})
});

Book.getByCategory({category: 'cheese'}).then(results) {
  results.forEach((book) => console.log(book.toJSON());
}).catch((err) => {
  //...
});
let SQL = require('sql-template-strings');

//sql-template-strings template tag returns a {text, values} object
//which gets turned into a prepare statement by gatepost
Book.fromSQL({
  name: 'insert',
  //using a template string
  sql: (args, model) => SQL`INSERT INTO books
(title, author, category)
VALUES (${model.title}, ${model.author}, ${model.category})
RETURNING id`,
  instance: true,
  oneResult: true
});

let book = Book.create({title: 'Ham and You', author: 'Nathan Fritz', category: 'ham'});

//using promises
book.insert()
.then((result) => console.log(`Book ID: ${book.id}`))
.catch((error) => console.log(`Gadzoons and error! ${error}`));

setConnection

Configure the pg postgres client with gatepost to use for queries. Accepts anything valid in the first parameter of pg.connect.

Running Tests

Either create a database called testdb or cp config/default.json config/local.json and update the uri.

Then run npm test

LICENSE

The MIT License (MIT)

Copyright (c) 2015 Nathanael C. Fritz

See LICENSE for the full text.

gatepost's People

Contributors

fritzy avatar latentflip avatar nlf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

nlf latentflip

gatepost's Issues

Mark pg client as done

Right now the connection client doesn't get marked as done, so we could easily fill the pool.

db hint

This is how the database code should never be written:

Book.fromSQL({
  name: 'insert',
  //using a template string
  sql: (args, model) => SQL`INSERT INTO books
(title, author, category)
VALUES (${model.title}, ${model.author}, ${model.category})
RETURNING id`,
  instance: true,
  oneResult: true
});

Why? Because ES6 template string formatting has no knowledge of how to convert JavaScript types into PostgreSQL-compliant data types. Only a postgres library would know that and provide a compliant type formatting.

For example, if any of your properties title, author or category contain a single-quote symbol ', it would immediately break the query. And there can be many examples like that.

Integration with knex query builder breaks if `'` in values

So knex has a bug: knex/knex#828, which means that calling toString() on a postgres query results in strings with ' escaped like \' instead of '' which is how postgres likes it.

Obviously it'd be nice for that to get fixed in knex, but the issues been kicking around for a while, and even has a (complex looking) PR against it, so I'm not sure what the progress there will be.

The alternative is that we integrate the query with the pg client in much the same way that knex does when it makes queries internally (it doesn't use toString, but sends queries along with bindings). That way the postgres client seems to handle converting JS's \' => PG's '' itself.

add a required flag for oneArg methods

if oneArg is set and required is true, then raise an error if no results are returned. this would prevent having to manually 404 in a handler (it should raise an error that would result in a 404 when combined with pgboom)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.