Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Last active April 3, 2017 08:24
Show Gist options
  • Save alexandrebodin/d657abb80114c24158910178b5b82715 to your computer and use it in GitHub Desktop.
Save alexandrebodin/d657abb80114c24158910178b5b82715 to your computer and use it in GitHub Desktop.
var R = require('ramda');
var db = require('./db/queries');
const a = db.filterUser({}, {})
.addContact('contact')
.addCompany(['contact', 'company'])
.then(res => {
console.log(res.splice(0, 1))
});
var R = require('ramda');
var knex = require('./knex');
const { addModifiers } = require('./queryWrapper');
const { resolveUser, resolveContact } = require('./resolvers');
// queries
const filterUser = (filters, sqlParams) => knex('user').select('beuz.*')
const modifiers = {
addContact(query) {
return query.modify(withEntity, 'contact', 'user.contact_id')
},
addCompany(query) {
return query.modify(withEntity, 'company', 'contact.company_id')
}
}
module.exports = exports = {
filterUser: addModifiers(filterUser, modifiers, resolveUser)
}
const R = require('ramda');
const knex = require('./knex');
const withEntity = (qb, table, fk, alias = table) => qb.leftJoin(table, fk, `${table}.id`).select(knex.raw(`to_json(${table}) ${alias}`))
const wrapModifiers = (modifiers) => {
return Object.keys(modifiers).reduce((acc, key) => {
return Object.assign(acc, {
[key]: function(path) {
if (!path || path.length === 0) throw Error('You must provide a valid path (String | Array<String>)');
const finalPath = Array.isArray(path) ? path : [path];
const resKey = finalPath.slice(-1);
if (this.mappings[resKey]) throw new Error(`Modifier "${key}" was called twice`);
this.mappings[resKey] = finalPath;
this.query = modifiers[key](this.query);
return this;
}
});
}, {});
}
const addModifiers = (fn, methods, resolver = R.identity) => {
return (...args) => {
return Object.assign({}, wrapModifiers(methods), {
mappings: {},
query: fn(...args),
then(...args) {
return this.query
.map(row => {
const keys = Object.keys(this.mappings);
return keys.reduce((acc, key) => R.assocPath(this.mappings[key], row[key], acc), R.omit(keys, row));
})
.map(resolver)
.then(...args);
}
})
}
}
module.exports = {
withEntity,
addModifiers
};
const resolveContact = contact => ({
id: contact.id,
firstname: contact.firstname,
lastname: contact.lastname,
company: contact.company ? contact.company : null
});
const resolveUser = user => Object.assign({}, {
id: user.id
}, {
contact: user.contact ? resolveContact(user.contact) : null,
})
module.exports = {
resolveContact,
resolveUser
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment