Skip to content

Commit

Permalink
Fix partial query enabled check and add error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
blenderskool committed Jan 19, 2022
1 parent 722f143 commit 107a2b8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
24 changes: 15 additions & 9 deletions lib/middlewares/partial-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,22 @@ export interface PartialQueryOptions extends MiddlewareOptions {};
export function partialJsonQuery(filterString: string) {
return async (req: NextApiRequest, res: NextApiResponse, next: Function) => {
const resultBuffer = await getStream.buffer(req.locals.result.data);
const resultData = mask(JSON.parse(resultBuffer as any), filterString);
// Below code is prone to errors if the body did not contain valid JSON data
try {
const resultData = mask(JSON.parse(resultBuffer as any), filterString);

const resultReadable = new Readable();
resultReadable.push(JSON.stringify(resultData));
resultReadable.push(null);
const resultReadable = new Readable();
resultReadable.push(JSON.stringify(resultData));
resultReadable.push(null);

req.locals.result = {
headers: { 'content-type': 'application/json' },
data: resultReadable,
};
next();
req.locals.result = {
headers: { 'content-type': 'application/json' },
data: resultReadable,
};
} catch(_) {
// Handle errors here if _necessary_ in the future
} finally {
next();
}
};
}
7 changes: 6 additions & 1 deletion pages/api/v1/[..._path].ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// Request made
try {
const startTime = performance.now();
const isPartialQueryEnabled = !!apiRoute.partialQuery.enabled || requestUrl.searchParams.has('diode-filter');
const isPartialQueryEnabled = !!apiRoute.partialQuery.enabled && requestUrl.searchParams.has('diode-filter');
const apiResponse = await axios.request({
method: apiRoute.method,
url: requestUrl.toString(),
Expand All @@ -95,6 +95,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
req.locals.result = apiResponse;

if (isPartialQueryEnabled && apiResponse.headers['content-type'].includes('application/json')) {
/**
* get() is used instead of getAll() as only the filter configured
* either in dashboard or the incoming query param is used.
* Not both to avoid confusion
*/
await runMiddleware(req, res, middlewares.partialJsonQuery(requestUrl.searchParams.get('diode-filter')));
}

Expand Down

0 comments on commit 107a2b8

Please sign in to comment.