Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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