Guest User

Untitled

a guest
Nov 27th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. const _ = require('lodash')
  2. const { Client } = require('pg')
  3.  
  4. // CONFIGURATION
  5. const client = new Client({
  6. host: process.env.PG_HOST,
  7. port: process.env.PG_PORT,
  8. user: 'admin',
  9. password: process.env.PG_PASSWORD,
  10. database: 'app-development'
  11. })
  12.  
  13. client.connect()
  14.  
  15. const query = (q,cb) => {
  16. client.query(q).then(res => {
  17. cb(res)
  18. }).catch( (err) => {
  19. cb(null,err)
  20. })
  21. }
  22.  
  23. // NORMALIZERS
  24. const unflatten = function(a, b, c) {
  25. (c = "undefined" == typeof c ? [] : c),
  26. (b = "undefined" == typeof b ? { id: 0 } : b);
  27. var d = _.filter(a, function(e) {
  28. return e.parent_id == b.id;
  29. });
  30. return (
  31. _.isEmpty(d) ||
  32. (0 == b.id ? (c = d) : (b.children = d),
  33. _.each(d, function(e) {
  34. unflatten(a, e);
  35. })),
  36. c
  37. );
  38. }
  39.  
  40. const queries = {
  41.  
  42. login: (email,passord,cb) => {
  43. query(`SELECT * FROM users WHERE email = "${email}"`, (res,err) => {
  44.  
  45. })
  46. },
  47.  
  48. item: (slug, cb) => {
  49.  
  50. const q = `
  51. WITH RECURSIVE tree AS (
  52.  
  53. SELECT
  54. "items".*
  55. 0::bigint as parent_id
  56. FROM "items"
  57. INNER JOIN "friendly_id_slugs"
  58. ON "friendly_id_slugs"."sluggable_id" = "items"."id" AND "friendly_id_slugs"."sluggable_type" = "Item"
  59. WHERE
  60. "friendly_id_slugs"."sluggable_type" = 'Item'
  61. AND
  62. "friendly_id_slugs"."slug" = "${slug}")
  63. ORDER BY "items"."id" ASC LIMIT 1
  64.  
  65. UNION ALL
  66.  
  67. SELECT
  68. it.*,
  69. t.id as parent_id
  70. FROM items as it, tree as t
  71. INNER JOIN item_children as itc
  72. ON t.id = itc.item_id
  73. WHERE itc.child_id = it.id
  74.  
  75. )
  76. SELECT * FROM tree
  77. `
  78. query( q, (res,err) => {
  79. cb(unflatten(res.rows))
  80. })
  81. }
  82. }
  83.  
  84. module.exports = queries
Add Comment
Please, Sign In to add comment