UNPKG

@speakr/speakr-module-services

Version:
143 lines (120 loc) 3.12 kB
"use strict"; const db = require('../../db/'); const hash = require('../../utils/hash'); module.exports = { index, byNetworkIdHash, byId, byNameOrCreate, byCampaignAgencyId }; function index(options) { return db.agencies.findAll( { order: [ ['name', 'ASC'] ] , include: [ { model: db.networks } ] }) .then(agencies => { if(!!agencies) { options.agencies = agencies; return Promise.resolve(options); } }).catch(err => { return Promise.reject(err); }); } function byNetworkIdHash(options) { return db.networks.find({ where: { id_hash: options.req.params.network_id_hash }, attributes: ['id'] }).then(network => { if(!network) { return Promise.reject({ code: 404, message: `Could not find the network with the network id hash of ${options.req.params.network_id_hash}`, purpose: "Network id hash could not be found" }); } const network_id = network.dataValues.id; const where = network_id === 1 ? {} : {network_id: network_id}; return db.agencies.findAll( { where: where, include: [db.networks] }) .then(agencies => { if(!!agencies) { options.agencies = agencies; return Promise.resolve(options); } }).catch(err => { return Promise.reject({ code: 400, message: `Could not find any agencies for the network id of ${options.req.params.network_id_hash}`, purpose: "Network has no agencies" }); }); }); } function byId(options) { let where = { id: options.users.agency_id }; return db.agencies.findOne(where) .then((agencies) => { delete options.users.agency_id; if(!!agencies) { options.agencies = agencies; return Promise.resolve(options); } else { return Promise.resolve(options); } }) } function byNameOrCreate(options) { let where = { id_hash: options.req.body.network_id_hash }; return db.networks.findOne({where}) .then(networks => { where = { name: options.req.body.agency }; return db.agencies.findOne({ where }) .then((agencies) => { if(!!agencies) { options.agencies = agencies; return Promise.resolve(options); } else { let id_hash = hash.generate; let create = { name: options.req.body.agency, id_hash: id_hash(), network_id: networks.id }; return db.agencies.create(create) .then(agencies => { options.agencies = agencies; return Promise.resolve(options); }) } }) }); } function byCampaignAgencyId(options) { return db.agencies.findAll({ where: { id: {$in: options.campaigns.map(campaign => campaign.agency_id)}}, attributes: ['id', 'name'] }).then(agencies => { if(!!agencies) { options.agencies = agencies; return Promise.resolve(options) } else { return Promise.resolve(options) } }).catch(err => { return Promise.reject(err); }); }