Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. var R = require('ramda');
  2. var knex = require('knex')({
  3. client: 'pg',
  4. connection: {
  5. host: 'localhost',
  6. port: '35432',
  7. database: 'vamos',
  8. password: 'vamos',
  9. user: 'vamos',
  10. }
  11. });
  12.  
  13.  
  14. const withEntity = (qb, table, fk, alias = table) => qb.leftJoin(table, fk, `${table}.id`).select(knex.raw(`to_json(${table}) ${alias}`))
  15.  
  16. const queryWrapper = (query, resolver) => {
  17.  
  18. let mappings = {};
  19.  
  20. return {
  21. query,
  22. addContact(...path) {
  23. if (mappings.contact) throw new Error('addContact called twice');
  24. mappings.contact = path.length > 0 ? R.flatten(path) : ['contact'];
  25.  
  26. query.modify(withEntity, 'contact', 'beuz.contact_id')
  27. return this;
  28. },
  29. addCompany(...path) {
  30. if (mappings.company) throw new Error('addCompany called twice');
  31. mappings.company = path.length > 0 ? R.flatten(path) : ['company'];
  32.  
  33. query.modify(withEntity, 'company', 'contact.company_id')
  34. return this;
  35. },
  36. then(...args) {
  37. return query
  38. .map(row => {
  39. const keys = Object.keys(mappings);
  40. return keys.reduce((acc, key) => R.assocPath(mappings[key], row[key], acc), R.omit(keys, row));
  41. })
  42. .map(resolver)
  43. .then(...args);
  44. }
  45. }
  46. }
  47.  
  48.  
  49. const contactR = contact => ({
  50. id: contact.id,
  51. firstname: contact.firstname,
  52. lastname: contact.lastname,
  53. company: contact.company
  54. });
  55.  
  56. const resolver = beuz => ({
  57. id: beuz.id,
  58. contact: contactR(beuz.contact),
  59. })
  60.  
  61. const db = {
  62. getBeuz(filters, sqlParams) {
  63. return queryWrapper(knex('beuz').select('beuz.id').where('beuz.id', 1), resolver);
  64. },
  65. }
  66.  
  67. const a = db.getBeuz({}, {})
  68. .addContact()
  69. .addCompany(['contact', 'company'])
  70. .then(res => {
  71. console.log(res);
  72. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement