Last active
April 26, 2020 00:31
-
-
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 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
// | |
// 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 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
// | |
// 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