Loader.prototype.normalize = function (opts, acc, value, key) { debug('normalize', key); if (opts && opts.normalize) { return opts.normalize(acc, value, key); } if (!value.ext) { var ext = path.extname(value.path); if (ext) value.ext = ext; } if (value.path && opts && opts.relative !== false) { value.path = relative(value.path); } value.content = value.content ? value.content.trim() : null; value = omitEmpty(value); if (!value.hasOwnProperty('content')) { console.log(chalk.red('missing `content` property: ' + JSON.stringify(arguments))); throw new Error('load-templates#normalize: expects templates to have a content property.'); } if (!value.hasOwnProperty('path')) { console.log(chalk.red('missing `path` property: ' + JSON.stringify(arguments))); throw new Error('load-templates#normalize: expects templates to have a path property.'); } // Rename the object key acc[this.renameKey(key, opts)] = value; return acc; };
_doCreate(user) { return this._createStripeCustomer(omitEmpty({ source: this.stripeToken, // obtained with Stripe.js email: user.email, metadata: { referredOf: this.clickIdAffiliateRef } })); }
function discoverFieldsFromRequestMetadata(requestMetadata) { const cfIpAddress = (requestMetadata['X-Forwarded-For'] || ',').split(',').shift().trim(); const acceptLanguage = (requestMetadata['Accept-Language'] || ',').split(',').shift().trim(); const language = (acceptLanguage || '_').split(/\-|_/).shift().trim(); const updatedMetadata = omitEmpty({ ip: cfIpAddress, countryCode: requestMetadata['CloudFront-Viewer-Country'], acceptLanguageHeader: requestMetadata['Accept-Language'], acceptLanguage, language, detectedDevice: findDetectedDevice(requestMetadata), userAgent: requestMetadata['User-Agent'] }); if (updatedMetadata.userAgent.match(/Zapier/)) return Promise.resolve({}); return request(`http://pro.ip-api.com/json/${cfIpAddress}?key=${process.env.IP_API_KEY}`) .then(result => JSON.parse(result)) .then(geoLocationData => omitEmpty(Object.assign({}, updatedMetadata, { countryName: geoLocationData.country, regionCode: geoLocationData.region, regionName: geoLocationData.regionName, city: geoLocationData.city, zipCode: geoLocationData.zip, timeZone: geoLocationData.timezone, location: { lat: geoLocationData.lat, lon: geoLocationData.lon } }))).catch(error => { console.log(error); Promise.resolve({}) }); // Avoid breaking the request if freegeoip fails }
.then((inlinedBody) => { resolve(omitEmpty({ userId: campaign.userId, userPlan: this.userPlan, appendFooter: this.appendFooter, currentUserState: this.currentState, campaign: { id: campaign.id, subject: campaign.subject, name: campaign.name, body: inlinedBody, senderId: campaign.senderId, precompiled: false, listIds: campaign.listIds, attachments: campaign.attachments, metadata: campaignMetadata, scheduledAt: campaign.scheduledAt }, user: { id: this.userId, phoneNumber: this.userPhone, notifications: this.userNotifications } })); });
unsubscribeRecipient() { const { listId, recipientId } = this.emailMetadata; if (this.shouldUnsubscribe()) { const recipient = { status: this.newStatus }; recipient[`${this.newStatus}At`] = moment().unix(); return Recipient.update(omitEmpty(recipient), listId, recipientId); } return Promise.resolve({}); }
export default function respond(event, cb) { logger().info('= getSubscriptionDetails.action', JSON.stringify(event)); return Promise.resolve(omitEmpty(event)) .then(params => Subscriptions.billingPlans.getPlan(params.plan)) .then(result => cb(null, result)) .catch((error) => { logger().error('= getSubscriptionDetails.action', error); cb(error); }); }
getResponse() { let resp = { links: this.getLinks() }; resp = _.merge({}, resp, this.data); resp.linked = this.linked; return omitEmpty(resp); }
function listSegmentMembers(event, context, callback) { App.configureLogger(event, context); App.logger().info('listSegmentMembers', JSON.stringify(event)); const options = event.options || {}; return Api.getSegmentMembers(event.listId, event.segmentId, omitEmpty(options)) .then(members => callback(null, members)) .catch((err) => { App.logger().error(err); callback(err); }); }
function buildApiResponse({ statusCode, body = {}, headers = {} }, callback) { const response = { statusCode, headers: omitEmpty(Object.assign({}, { 'Access-Control-Allow-Origin': '*', // Required for CORS support to work 'Access-Control-Allow-Credentials': true // Required for cookies, authorization headers with HTTPS }, headers)), body: JSON.stringify(body) }; callback(null, response); }
export default function respond(event, cb) { logger().info('= getTotalRecipientsHttp.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => getTotalRecipients(decoded.sub)) .then(total => cb(null, total)) .catch((err) => { logger().error(err); return errorHandler(err, [], cb); }); }
export default function respond(event, cb) { logger().info('= updateAutomation.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken', 'automationId', 'automation']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => updateAutomation(decoded.sub, event)) .then(automation => cb(null, automation)) .catch((err) => { logger().error(err); return errorHandler(err, [], cb); }); }
function create({ status, message, createdAt, finishedAt }) { return omitEmpty({ // Legacy to be deprecated in the future importing: status === 'importing', // Attributes to keep status, createdAt, finishedAt, // In case of error, the error message message }); }
export default function respond(event, cb) { logger().info('= updateCard.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken', 'token']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => Subscriptions.attachUserCard(decoded.sub, event.token)) .then(result => cb(null, result)) .catch((error) => { logger().error('= handleSubscription.action', error, error.stack); return errorHandler(Subscriptions.handleStripeErrors(error), ['PaymentError'], cb); }); }
decrypt(event.authToken).then((decoded) => { let cleanOptions = omitEmpty(event.options); cleanOptions.limit = cleanOptions.limit ? parseInt(cleanOptions.limit, 10) : 10; List.allBy('userId', decoded.sub, cleanOptions).then(list => { debug('= listEmailLists.action', 'Success'); return cb(null, list); }) .catch(e => { debug('= listEmailLists.action', e); return cb(ApiErrors.response(e)); }); })
.then(geoLocationData => omitEmpty(Object.assign({}, updatedMetadata, { countryName: geoLocationData.country, regionCode: geoLocationData.region, regionName: geoLocationData.regionName, city: geoLocationData.city, zipCode: geoLocationData.zip, timeZone: geoLocationData.timezone, location: { lat: geoLocationData.lat, lon: geoLocationData.lon } }))).catch(error => { console.log(error); Promise.resolve({}) }); // Avoid breaking the request if freegeoip fails
async function updateRecipient(event, context, callback) { try { App.configureLogger(event, context); App.logger().info('updateRecipient', JSON.stringify(event)); const params = JSON.parse(event.body); const user = await UserContext.byApiKey(event.requestContext.identity.apiKey); await Api.publishRecipientUpdatedEvent(omitEmpty({ listId: event.pathParameters.listId, userId: user.id, recipientId: event.pathParameters.recipientId, updateRecipientPayload: params })); HttpUtils.buildApiResponse({ statusCode: 202 }, callback); } catch (error) { App.logger().error(error); HttpUtils.apiErrorHandler(error, callback); } }
export async function respond(event, cb) { debug('= accessAuthorizedAccount.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken', 'userId']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => authorize(decoded.sub, decodeURIComponent(event.userId))) .then(userIds => impersonate(userIds, event)) .then(url => cb(null, {url})) .catch(err => { console.error(err); return errorHandler(err, [], cb) }); }
.then(geoLocationData => omitEmpty(Object.assign({}, updatedMetadata, { countryName: geoLocationData.country_name, regionCode: geoLocationData.region_code, regionName: geoLocationData.region_name, city: geoLocationData.city, zipCode: geoLocationData.zip_code, timeZone: geoLocationData.time_zone, location: { lat: geoLocationData.latitude, lon: geoLocationData.longitude }, metroCode: geoLocationData.metro_code }))).catch(error => Promise.resolve({})); // Avoid breaking the request if freegeoip fails
async function createRecipient(event, context, callback) { try { App.configureLogger(event, context); App.logger().info('createRecipient', JSON.stringify(event)); const { recipient } = JSON.parse(event.body); const user = await UserContext.byApiKey(event.requestContext.identity.apiKey); await Api.publishRecipientCreatedEvent(omitEmpty({ listId: event.pathParameters.listId, userId: user.id, createRecipientPayload: recipient, subscriptionOrigin: RecipientModel.subscriptionOrigins.api })); const recipientId = Recipients.buildId(recipient); const recourceLocation = `/${event.pathParameters.listId}/recipients/${recipientId}`; HttpUtils.buildApiResponse({ statusCode: 202, headers: { Location: recourceLocation }, body: { recipient: { id: recipientId } } }, callback); } catch (error) { App.logger().error(error); HttpUtils.apiErrorHandler(error, callback); } }
function recursiveScan(tableName, exclusiveStartKey = {}) { const credentials = new AWS.SharedIniFileCredentials({ profile: settings[stage].profile }); AWS.config.credentials = credentials; const dynamoConfig = { region: settings[stage].region }; const db = new AWS.DynamoDB.DocumentClient(dynamoConfig); const scanParams = omitEmpty({ TableName: settings[stage].tableName, ExclusiveStartKey: exclusiveStartKey }); return db.scan(scanParams).promise() .then((result) => { if (result.LastEvaluatedKey) return recursiveScan(tableName, result.LastEvaluatedKey).then(items => result.Items.concat(items)); return result.Items; }); }
export default function respond(event, cb) { logger().info(JSON.stringify(event)); const signupUrl = process.env.SIGNUP_URL; return getRegistrationToken(omitEmpty(event)) .then(token => AmazonSubscriptions.resolveCustomer(token)) .then(azCustomer => { logger().info('AZ Customer', azCustomer); const url = `${signupUrl}?amazonCustomerId=${azCustomer.CustomerIdentifier}`; cb(null, {url}); }) .catch((error) => { logger().error(error); cb(null, {url: signupUrl}); }); }
export default function respond(event, cb) { logger().info('= handleSubscription.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken', 'billingPlan']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => Subscriptions.updateUserSubscription(decoded.sub, event.billingPlan, event.subscriptionType || 'monthly', event.token, event.clickId)) .then(result => cb(null, result)) .catch((error) => { logger().error('= handleSubscription.action', error); if (error.name === 'PaymentGatewayError') { return errorHandler(newError(error.name, error.message, 401), ['PaymentGatewayError'], cb); } return errorHandler(error, [], cb); }); }
static _doCreate(listId, recipient, userId) { const subscriptionOrigin = Recipient.subscriptionOrigins.signupForm; const recipientParams = Object.assign({}, { listId, subscriptionOrigin }, omitEmpty(recipient)); recipientParams.id = base64url.encode(recipient.email); return List.get(userId, listId).then((list) => { if (list.hasOwnProperty('sendEmailVerificationOnSubscribe')) { if (JSON.parse(list.sendEmailVerificationOnSubscribe) === false) { recipientParams.status = Recipient.statuses.subscribed; return Recipient.save(recipientParams).then(() => recipientParams); } } recipientParams.verificationCode = this._generateVerificationCode(); recipientParams.status = Recipient.statuses.awaitingConfirmation; return Recipient.save(recipientParams).then(() => recipientParams); }); }
decrypt(event.authToken).then((decoded) => { const options = { limit: 10 }; if (event.options) { Object.assign(options, omitEmpty(event.options)); } Campaign.allBy('userId', decoded.sub, options).then(campaigns => { debug('= listCampaigns.action', 'Success'); return cb(null, campaigns); }) .catch(e => { debug('= listCampaigns.action', e); return cb(ApiErrors.response(e)); }); })
export default function respond(event, cb) { logger().info('= searchRecipientsHttp.action', JSON.stringify(event)); const checkParams = paramsChecker(['authToken', 'conditions']); return checkParams(omitEmpty(event)) .then(params => decrypt(params.authToken)) .then(decoded => searchRecipients(event)) .then(results => cb(null, results)) .catch((err) => { logger().error(err); // Even search is based upon segments if (err.name === 'ListSegmentError') { return errorHandler(newError('ConditionsFormatError', err.message, 401), { customErrorNames: ['ConditionsFormatError'] }, cb); } return errorHandler(err, [], cb); }); }
get emailMetadata() { const payloadHeadersMapping = { listId: 'X-Moonmail-List-ID', recipientId: 'X-Moonmail-Recipient-ID', campaignId: 'X-Moonmail-Campaign-ID' }; const headerValue = header => R.pipe( R.find(R.propEq('name', header)), el => el ? el : {}, R.prop('value') )(this.headers); const metadata = Object.keys(payloadHeadersMapping).reduce((acc, key) => { const newObj = { [key]: headerValue(payloadHeadersMapping[key]) }; return Object.assign({}, acc, newObj); }, {}); return omitEmpty(metadata); }
_.each(element, function (train, property_index,list){ var params = { TableName: process.env.AWS_DYNAMODB_TABLE_NAME_TRAINS, Item: { } }; params.Item = train params.Item.routeName = index; params.Item.arrT = moment.tz(params.Item.arrT, "YYYYMMDD HH:mm:ss", "America/Chicago").unix(); params.Item.prdt = moment.tz(params.Item.prdt, "YYYYMMDD HH:mm:ss", "America/Chicago").unix(); params.Item.geohash = geohash.encode(params.Item.lat, params.Item.lon, 9); docClient.put(omitEmpty(params), function(err, data) { console.log(params) if (err) console.error(JSON.stringify(err, null, 2)); }); });
export function respond(event, cb) { debug('= unsubscribeRecipient.action', JSON.stringify(event)); if (event.listId && event.recipientId) { const recipient = { status: Recipient.statuses.unsubscribed, unsubscribedAt: moment().unix(), unsubscribedCampaignId: event.campaignId }; Recipient.update(omitEmpty(recipient), event.listId, event.recipientId).then((newRecipient) => { debug('= unsubscribeRecipient.action', 'Success'); const recipientParams = { campaignId: event.campaignId, userId: newRecipient.userId, listId: event.listId }; const params = { Message: JSON.stringify(recipientParams), TopicArn: process.env.UNSUBSCRIBED_RECIPIENT_TOPIC_ARN }; sns.publish(params, (err, data) => { if (err) { debug('= unsubscribeRecipient.action', 'Error publishing to SNS', JSON.stringify(err)); return cb(ApiErrors.response(err)); } else { debug('= unsubscribeRecipient.action', 'Successfully published to SNS'); List.get(newRecipient.userId, event.listId).then((list) => { const callbackUrl = buildRedirectCallback(process.env.UNSUBSCRIBED_CALLBACK_URL, list, event.recipientId, event.campaignId); return cb(null, { url: callbackUrl }); }).catch((e) => { const callbackUrl = process.env.UNSUBSCRIBED_CALLBACK_URL; return cb(null, { url: callbackUrl }); }); } }); }) .catch((e) => { debug('= unsubscribeRecipient.action', e); return cb(e); }); } else { return cb('No recipient specified'); } }
buildEmail(sender, recipient, eventPayload = {}) { return omitEmpty({ email: { body: this.automationAction.campaign.body, subject: this.automationAction.campaign.subject }, metadata: { campaignId: this.automationAction.id, automationActionId: this.automationAction.id, automationId: this.automationAction.automationId, listId: recipient.listId, userId: this.automationAction.userId, segmentId: eventPayload.segmentId }, sender, recipient, delay: this.automationAction.delay }); }
decrypt(event.authToken).then((decoded) => { if (event.listId) { let options = { limit: 10 }; if (event.options) { Object.assign(options, omitEmpty(event.options)); } Recipient.allBy('listId', event.listId, options).then(recipients => { debug('= listRecipients.action', 'Success'); return cb(null, recipients); }) .catch(e => { debug('= listRecipients.action', e); return cb(ApiErrors.response(e)); }); } else { return cb(ApiErrors.response('No list provided')); } })