fix: let's try to refactor shutdown again, again
This commit is contained in:
parent
0b5f0c5d5e
commit
a9b20fea40
4 changed files with 196 additions and 9 deletions
86
tests/www/api/events/index.ts
Normal file
86
tests/www/api/events/index.ts
Normal file
|
@ -0,0 +1,86 @@
|
|||
type EVENT = {
|
||||
value: string;
|
||||
timestamp: string;
|
||||
};
|
||||
|
||||
const events: EVENT[] = [];
|
||||
|
||||
export function GET(request: Request, meta: Record<string, any>): Promise<Response> | Response {
|
||||
function get_events() {
|
||||
return events.filter((event) => meta.query.after ? event.timestamp > meta.query.after : true);
|
||||
}
|
||||
|
||||
const results = get_events();
|
||||
|
||||
// long-polling support
|
||||
if (results.length === 0 && meta.query.wait) {
|
||||
const last_event = events.at(-1);
|
||||
return new Promise((resolve, reject) => {
|
||||
let timeout: number | undefined;
|
||||
|
||||
const final_timeout = setTimeout(() => {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
resolve(Response.json([], {
|
||||
status: 200
|
||||
}));
|
||||
}, 60_000); // 60 seconds max wait
|
||||
|
||||
(function check_for_new_events() {
|
||||
const latest_event = events.at(-1);
|
||||
if (latest_event !== last_event) {
|
||||
clearTimeout(final_timeout);
|
||||
if (timeout) clearTimeout(timeout);
|
||||
return resolve(Response.json(get_events(), {
|
||||
status: 200
|
||||
}));
|
||||
}
|
||||
|
||||
timeout = setTimeout(check_for_new_events, 1_000);
|
||||
})();
|
||||
|
||||
request.signal.addEventListener('abort', () => {
|
||||
clearTimeout(final_timeout);
|
||||
if (timeout) clearTimeout(timeout);
|
||||
reject(new Error('request aborted'));
|
||||
});
|
||||
|
||||
Deno.addSignalListener('SIGINT', () => {
|
||||
clearTimeout(final_timeout);
|
||||
if (timeout) clearTimeout(timeout);
|
||||
return resolve(Response.json(results, {
|
||||
status: 200
|
||||
}));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json(results, {
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(req: Request, _meta: Record<string, any>): Promise<Response> {
|
||||
try {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const body = await req.json();
|
||||
const event: EVENT = {
|
||||
value: '',
|
||||
...body,
|
||||
timestamp: now
|
||||
};
|
||||
|
||||
events.push(event);
|
||||
|
||||
return Response.json(event, {
|
||||
status: 201
|
||||
});
|
||||
} catch (error) {
|
||||
return Response.json({
|
||||
error: {
|
||||
message: (error as Error).message ?? 'Unknown Error!',
|
||||
cause: (error as Error).cause ?? 'unknown'
|
||||
}
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue