Created
April 24, 2020 04:00
-
-
Save RealDyllon/2a412971d7ae7f625a84752d050c4232 to your computer and use it in GitHub Desktop.
Nodejs Serverless code for https://github.com/RealDyllon/react-supermarket-tracker
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
const https = require('https'); | |
const querystring = require('querystring'); | |
exports.handler = async(event) => { | |
let dataString = ''; | |
const httpOrigin = event.headers.origin | |
const allowedOrigins = [ | |
"https://supermarkets.dyllon.dev" | |
] | |
const isAllowed = allowedOrigins.indexOf(httpOrigin) > -1 | |
// grab our params from the lambda proxy integration | |
const reqParamsData = { | |
postal_code: (event && | |
event.queryStringParameters) ? | |
event.queryStringParameters.postcode : "000000" | |
} | |
// console.log("postcode", reqParamsData.postal_code) | |
const reqParams = querystring.stringify(reqParamsData); | |
const reqOptions = { | |
hostname: 'giant.sg', | |
path: '/checkout/cart/checkdelivery?' + reqParams, | |
headers: { | |
} | |
} | |
const response = await new Promise((resolve, reject) => { | |
// define the https request | |
https.get(reqOptions, res => { | |
//append to data string in real time | |
res.on('data', chunk => { | |
// console.log("chunk", chunk) | |
dataString += chunk; | |
}); | |
//when we've got all the data: | |
res.on('end', () => { | |
// console.log("dataString", (dataString)) | |
let dataObj = JSON.parse(dataString) | |
console.log( | |
{ | |
postcode: reqParamsData.postal_code, | |
httpOrigin: httpOrigin | |
} | |
) | |
let outputString = JSON.stringify({ | |
...dataObj, | |
apiEcho: { | |
postcode: reqParamsData.postal_code === "000000" ? | |
"missing!!!" : reqParamsData.postal_code, | |
httpOrigin: httpOrigin | |
}, | |
event | |
}) | |
resolve({ | |
statusCode: 200, | |
headers: { | |
"Access-Control-Allow-Origin": | |
isAllowed ? | |
httpOrigin | |
: "https://supermarkets.dyllon.dev", | |
"Access-Control-Allow-Headers": "Content-Type", | |
"Access-Control-Allow-Methods": "OPTIONS,POST,GET" | |
}, | |
body: outputString | |
}); | |
}); | |
}) | |
// abort in case of error | |
.on('error', (e) => { | |
reject({ | |
statusCode: 500, | |
headers: { | |
"Access-Control-Allow-Origin": isAllowed ? | |
httpOrigin : "https://supermarkets.dyllon.dev", | |
"Access-Control-Allow-Headers": "Content-Type", | |
"Access-Control-Allow-Methods": "OPTIONS,POST,GET" | |
}, | |
body: 'Something went wrong!' | |
}); | |
}); | |
}); | |
return response; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment