UNPKG

@speakr/speakr-module-services

Version:
153 lines (129 loc) 3.28 kB
"use strict"; const db = require('../../db/'); const hash = require('../../utils/hash'); module.exports = { index, byNetworkIdHash, byId, byNameOrCreate, byCampaignBrandnameId, byCampaignId }; function byId(options) { } function index(options) { return db.brands.findAll( { include: [ { model: db.networks } ] } ) .then(brands => { if(!!brands) { options.brands = brands; 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.brands.findAll( { where: where, include: [db.networks] }) .then(brands => { if(!!brands) { options.brands = brands; return Promise.resolve(options); } }).catch(err => { return Promise.reject({ code: 400, message: `Could not find any brands for the network id of ${options.req.params.network_id_hash}`, purpose: "Network has no brands" }); }); }); } function byNameOrCreate(options) { let where = { id_hash: options.req.body.network_id_hash }; return db.networks.findOne({where}) .then(networks => { let where = { name: options.req.body.brand }; return db.brands.findOne({ where }) .then(brands => { if(!!brands) { options.brands = brands; return Promise.resolve(options); } else { let id_hash = hash.generate; let create = { name: options.req.body.brand, id_hash: id_hash(), network_id: networks.id }; return db.brands.create(create) .then(brands => { options.brands = brands; return Promise.resolve(options); }) } }) }); } function byCampaignBrandnameId(options) { return db.brands.findAll({ where: { id: {$in: options.campaigns.map(campaign => campaign.brandname_id)}}, attributes: ['id', 'name'] }).then(brands => { if(!!brands) { options.brands = brands; return Promise.resolve(options) } else { return Promise.resolve(options) } }).catch(err => { return Promise.reject(err); }); } function byCampaignId(options) { const id = options.campaigns.dataValues ? options.campaigns.dataValues.brandname_id : options.campaigns.brandname_id; const where = { id }; return db.brands.findOne({ where }) .then(brand => { if(!brand) throw new Error('no brand') options.brands = brand.dataValues; return options; }) .catch(err => { return Promise.reject({ code: 404, message: 'Can not find brand', purpose: err.message }) }) }