Currently, I am in the process of developing a Next.js application, where I have defined an API as shown below:
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
fn1Get(req, res);
} else if (req.method === 'POST') {
fn1Post(req, res);
} else {
res.status(501).json({ operation: `${req.method}: not implemented` });
}
}
async function fn1Get(
req: NextApiRequest,
res: NextApiResponse
): Promise<void> {
const authenticated = await checkAuth(req, res);
if (authenticated) {
// Fetch Data
res.status(200).json({status: 'all good!'});
}
}
async function fn1Post(
req: NextApiRequest,
res: NextApiResponse
): Promise<void> {
const authenticated = await checkAuth(req, res);
if (authenticated) {
// Submit Data
res.status(201).json({status: 'all good!'});
}
}
const checkAuth = async (req: NextApiRequest, res: NextApiResponse) => {
const tokenValid = await extnernalApiCall(getToken(req));
if (!tokenValid) {
res.status(403).json({ error: 'Authentication Failed' });
}
return tokenValid
};
I am looking for a more efficient method to define authenticated functions, rather than including the line
const authenticated = await checkAuth(req, res);
within each function
In languages like Java or Python, decorators/annotations/AOP can be used for this purpose. Is there a similar approach in JavaScript? Perhaps by using function wrapping and/or bind/call/apply??
Conceptual example:
const checkAuth = async (fn) => {
const req = arguments[1];
const res = arguments[2];
const tokenValid = await extnernalApiCall(getToken(req));
if (!tokenValid) {
res.status(403).json({ error: 'Authentication Failed' });
}
return fn(arguments);
}
async function fn1Get = checkAuth(_fn1Get(
req: NextApiRequest,
res: NextApiResponse
): Promise<void> {
const authenticated = await checkAuth(req, res);
if (authenticated) {
// Fetch Data
res.status(200).json({status: 'all good!'});
}
})
All the functions that require authentication will have the same parameters req
and res
(request and response). The authentication function also needs these parameters to extract the token from req
and send a 403 error to res
if not authenticated
The technologies being used include Next.js with React 17, TypeScript, and ECMAScript 6