Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Proposal) implement db.one() #564

Closed
jniles opened this issue Jul 7, 2016 · 1 comment
Closed

(Proposal) implement db.one() #564

jniles opened this issue Jul 7, 2016 · 1 comment
Assignees

Comments

@jniles
Copy link
Collaborator

jniles commented Jul 7, 2016

Inspired by the pg-promise library, I propose that we implement a convenience function db.one(sql, params, tableName). db.one() will call db.exec() internally, but will ensure that only one result is returned.

Proposed behavior:

  1. If the db.exec() call returns no rows, throw a new NotFound() error with the tableName in the description.
  2. If the db.exec() call returns exactly one row, return rows[0]
  3. If the db.exec() call returns multiple rows, log a warning and return rows[0].

For example:

// on the accounts controller
function detail(req, res, next) {
  db.one('SELECT * FROM account WHERE id = ?', [req.params.id], 'account')
  .then(row => res.status(200).json(row))
  .catch(next)
  .done();
}

// in the purchase orders controller
function detail(req, res, next) {
  db.one(
    `SELECT p.uuid, p.date, p.supplier_uuid, pi.cost 
     FROM purchase p JOIN purchase_item pi ON p.uuid = pi.purchase_uuid 
     WHERE p.uuid = ?`, [req.params.uuid], 'purchase'
  )
  .then(row => res.status(200).json(row))
  .catch(next)
  .done()
}
@jniles jniles added this to the Future milestone Sep 22, 2016
@jniles jniles self-assigned this Sep 22, 2016
@jniles
Copy link
Collaborator Author

jniles commented Sep 22, 2016

I'll take this one to clean up the controller code for #694.

jniles referenced this issue in jniles/bhima Sep 22, 2016
This commit implements db.one() and changes a few controllers to use it
as a proof of work.  This allows logic for NotFound and BadRequest to be
implement in the `db` library instead of in each individual controller.

Closes #564.
jniles referenced this issue in jniles/bhima Sep 22, 2016
This commit implements db.one() and changes a few controllers to use it
as a proof of work.  This allows logic for NotFound and BadRequest to be
implement in the `db` library instead of in each individual controller.

Closes #564.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant