Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active April 26, 2020 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/c738a0dc76a41ec61ca071247588ac5c to your computer and use it in GitHub Desktop.
Save cferdinandi/c738a0dc76a41ec61ca071247588ac5c to your computer and use it in GitHub Desktop.
An example of how to automatically surface a unique discount code based on someone's location using Cloudflare Workers. https://workers.cloudflare.com/
//
// This part goes on Cloudflare Workers
//
addEventListener('fetch', function (event) {
event.respondWith(handleRequest(event.request));
});
/**
* Available discounts
*/
var discounts = {
US: {
location: 'United States',
locationCode: 'US',
discountAmount: 15,
discountCode: 'HIAMERICA',
},
CA: {
location: 'Canada',
locationCode: 'CA',
discountAmount: 33,
discountCode: 'HICANADA',
},
AU: {
location: 'Australia',
locationCode: 'AU',
discountAmount: 42,
discountCode: 'HIAUSTRALIA',
}
};
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
let headers = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': '*'
});
return new Response(JSON.stringify({
discount: discounts[request.cf.country]
}), {
status: 200,
headers: headers
});
};
//
// This part goes on your own website
//
var getLocation = function () {
fetch('https://discounts.gomakethings.workers.dev').then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
if (data.discount) {
// Show a discount code somewhere
// data is the discount details
}
}).catch(function(error) {
// Log a warning for debugging
console.warn(error);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment