Skip to content

Commit

Permalink
update functions
Browse files Browse the repository at this point in the history
  • Loading branch information
kresnasatya committed Dec 27, 2024
1 parent eb87923 commit 7af2d84
Showing 1 changed file with 31 additions and 10 deletions.
41 changes: 31 additions & 10 deletions functions/api/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
// import path from 'path';
// import fsPromises from 'fs/promises';

export async function onRequest(context) {
try {
// let result = [];
const url = new URL(context.request.url);

// Get query parameters using URLSearchParams
const month = url.searchParams.get('month') || '';
const year = url.searchParams.get('year') || (new Date()).getFullYear();
let response = new Response(JSON.stringify({ year, month }));
const responseText = await fetch(`https://raw.githubusercontent.com/kresnasatya/api-harilibur/refs/heads/main/data/${year}.json`);

if (responseText.ok) {
const rawData = await responseText.text();
let data = JSON.parse(rawData);
if (month) {
data = data.filter(item => {
if ((new Date(item.holiday_date)).getMonth() + 1 == month) {
return item;
}
});
}

let response = new Response(data);
response.headers.set('Cache-Control', 'public, max-age=0, s-maxage=86400');
response.headers.set('Content-Type', 'application/json');
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET');

response.headers.set('Cache-Control', 'public, max-age=0, s-maxage=86400');
response.headers.set('Content-Type', 'application/json');
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET');
return response;
} else {
let response = new Response(JSON.stringify({ error: responseText.statusText }), {
status: responseText.status
});
response.headers.set('Cache-Control', 'public, max-age=0, s-maxage=86400');
response.headers.set('Content-Type', 'application/json');
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET');

return response;
return response;
}
} catch (error) {
let response = new Response(JSON.stringify({ error: error.message }), {
status: error.statusCode || 500
Expand All @@ -26,5 +45,7 @@ export async function onRequest(context) {
response.headers.set('Content-Type', 'application/json');
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET');

return response;
}
}

0 comments on commit 7af2d84

Please sign in to comment.