Prevent cron monitor calls outside production, improve thrown error messages/API response

This commit is contained in:
Xevion
2023-02-25 00:14:13 -06:00
parent 891a767d6f
commit de18ce26f2
3 changed files with 105 additions and 79 deletions

View File

@@ -1,40 +1,49 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { getDistance } from "@/location";
import { env } from "@/env/server.mjs";
import monitorAsync from "@/monitor";
import type { NextApiRequest, NextApiResponse } from 'next';
import { getDistance } from '@/location';
import { env } from '@/env/server.mjs';
import monitorAsync from '@/monitor';
type ResponseData = {
diff: number;
inRange: boolean;
diff: number;
inRange: boolean;
};
type StatusData = { status: string };
const center = {
latitude: env.CENTER_LATITUDE,
longitude: env.CENTER_LONGITUDE,
latitude: env.CENTER_LATITUDE,
longitude: env.CENTER_LONGITUDE
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<(ResponseData & StatusData) | StatusData>
req: NextApiRequest,
res: NextApiResponse<(ResponseData & StatusData) | StatusData>
) {
if (req.query.key != env.API_KEY) {
// auth failed
res.status(401).json({ status: "Unauthorized" });
return;
}
if (req.query.key != env.API_KEY) {
// auth failed
res.status(401).json({ status: 'Unauthorized' });
return;
}
await monitorAsync(async function () {
const diff = await getDistance();
// auth passed
res.setHeader(
"Cache-Control",
`max-age=0, s-maxage=${env.EDGE_CACHE_TIME_SECONDS}, stale-while-revalidate`
);
res
.status(200)
.json({ diff, inRange: diff < env.MAX_DISTANCE, status: "Authorized" });
});
async function innerFunction() {
const diff = await getDistance();
// auth passed
res.setHeader(
'Cache-Control',
`max-age=0, s-maxage=${env.EDGE_CACHE_TIME_SECONDS}, stale-while-revalidate`
);
res
.status(200)
.json({ diff, inRange: diff < env.MAX_DISTANCE, status: 'Success' });
}
try {
if (process.env.NODE_ENV === 'production')
await monitorAsync(innerFunction);
else await innerFunction();
} catch (e) {
console.error(e);
res.status(500).json({ status: 'Error' });
}
}