Last active
November 16, 2017 09:43
-
-
Save cneijenhuis/58d071b88ddf77ddf63c1e787a88292b to your computer and use it in GitHub Desktop.
AWS Lambda code to add a default warehouse to a commercetools platform API request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const https = require('https'); | |
exports.handler = (event, context, callback) => { | |
const buffer = Buffer.from(event.body, 'base64'); | |
let requestBody = JSON.parse(buffer.toString()); | |
requestBody = setDefaultSupplyChannel(requestBody); | |
let requestBodyAsString = JSON.stringify(requestBody); | |
const options = { | |
hostname: 'api.sphere.io', | |
port: 443, | |
path: '/' + event.stageVariables.project_key + event.path, | |
method: event.httpMethod, | |
headers: event.headers | |
}; | |
options.headers.Host = 'api.sphere.io'; | |
const req = https.request(options, (res) => { | |
var chunks = []; | |
res.on('data', (chunk) => chunks.push(chunk)); | |
res.on('end', () => { | |
var buffer = Buffer.concat(chunks); | |
var responseBody = buffer.toString('base64'); | |
callback(null, { | |
"body": responseBody, | |
"isBase64Encoded": true, | |
"statusCode": res.statusCode, | |
"headers": res.headers | |
}); | |
}); | |
}); | |
req.on('error', callback); | |
req.write(requestBodyAsString); | |
req.end(); | |
}; | |
const setDefaultSupplyChannel = (requestBody) => { | |
requestBody.actions = requestBody.actions.map((action) => { | |
if (action.action == 'addLineItem') { | |
// CHECK #1: In doubt, deliver from the san francisco store. | |
if (typeof action.supplyChannel != 'Object') { | |
action.supplyChannel = { | |
'typeId' : 'channel', | |
'id' : 'e852da8d-e1b3-4628-9ac0-e0d3c4fb8523' | |
}; | |
console.log("added channel to line item") | |
} | |
} | |
return action; | |
}); | |
return requestBody; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment