export async function handler(context, request) {
const controller = new AbortController();
const TIMEOUT_MS = 3000;

const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);

try {
const method = (request.httpMethod || 'GET').toUpperCase();

const allowedBodyMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];
const hasBody = allowedBodyMethods.includes(method);

const bodyText = hasBody
? (request.body && request.body.length ? request.body : '{}')
: undefined;

// Проксируем запрос на GAS
const gasResponse = await fetch(
'https://script.google.com/macros/s/ID/exec', //ID приложения GAS
{
method,
headers: request.headers,
...(hasBody ? { body: Buffer.from(bodyText) } : {}),
redirect: 'manual',
signal: controller.signal
}
);

clearTimeout(timeout);

const text = await gasResponse.text();

const headersObj = {};
gasResponse.headers.forEach((value, key) => {
headersObj[key] = value;
});

return {
status: gasResponse.status,
headers: headersObj,
body: text
};

} catch (err) {
clearTimeout(timeout);

if (err.name === 'AbortError') {
return {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'timeout' })
};
}

return {
status: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'error', message: err.message })
};
}
}