Skip to content

Instantly share code, notes, and snippets.

@devbyray
Last active August 6, 2021 11:33
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 devbyray/dd1266d75f8a7c9f8f433cea4bf0f4e7 to your computer and use it in GitHub Desktop.
Save devbyray/dd1266d75f8a7c9f8f433cea4bf0f4e7 to your computer and use it in GitHub Desktop.
example-netlify-serverless.function.ts
import { Handler, HandlerContext, HandlerEvent } from '@netlify/functions';
import fetch from 'node-fetch';
import { client } from '../functions-utils/redis-client';
import { headers } from 'functions-utils/cors';
function getData(): Promise<any> {
return fetch(
'https://apiurl.com/data.json'
).then((res) => res.json());
}
const handler: Handler = async (
event: HandlerEvent,
) => {
try {
if (event.httpMethod === 'OPTIONS') {
return { statusCode: 200, headers, body: 'Ok' };
}
if (event.httpMethod !== 'PUT') {
return {
statusCode: 405,
headers,
body: JSON.stringify({ message: 'Method Not Allowed' }),
};
}
const allCountries = await getData();
const data = await client.set('countries', allCountries);
return {
statusCode: 200,
headers,
body: JSON.stringify({
message: 'All countries data',
data: JSON.parse(allCountries ?? '{}'),
}),
};
} catch (err) {
console.log('Error:', err);
return {
statusCode: 400,
headers,
body: JSON.stringify({ message: 'Error', err }),
};
}
};
export { handler };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment