-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: refactor API to use authentication and assertions
- Loading branch information
Jon Carlson
committed
Dec 11, 2024
1 parent
dc441d8
commit 1f3fc31
Showing
43 changed files
with
728 additions
and
707 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import { NextApiRequest, NextApiResponse } from 'next' | ||
import { ZodError } from 'zod' | ||
import createError from 'http-errors' | ||
import { parameterWithInflection } from './grammar' | ||
import log from './log' | ||
|
||
export function withApiErrorHandler(handler) { | ||
return async (req: NextApiRequest, res: NextApiResponse) => { | ||
try { | ||
// Call the original handler | ||
await handler(req, res) | ||
} catch (err) { | ||
// Any unhandled exceptions will be caught and reported as a clean JSON response | ||
return apiError(err, res) | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* converts errors to a JSON api response | ||
* To prevent leaking implementation details to an end-user, if the error isn't an instance of HttpError, only return a generic error. | ||
*/ | ||
export function apiError( | ||
error: Error | ZodError | createError.HttpError, | ||
response: NextApiResponse | ||
) { | ||
let interstitialError = error | ||
|
||
if (error.name === 'ZodError') { | ||
interstitialError = formatZodError(error as ZodError) | ||
} | ||
|
||
const safeError = | ||
interstitialError instanceof createError.HttpError | ||
? interstitialError | ||
: new createError.InternalServerError() | ||
|
||
if (safeError instanceof createError.InternalServerError) { | ||
// this is an unknown error, lets dump out the details so we can debug it later | ||
log.error(safeError) | ||
} | ||
|
||
return response.status(safeError.status).json({ | ||
status: safeError.status, | ||
error: safeError.message, | ||
}) | ||
} | ||
|
||
export function formatZodError(error: ZodError, messagePrefix?: string) { | ||
const errorString = error.issues.reduce((accumulator, current, index, self) => { | ||
//* We want spaces between errors but not for the last error. | ||
const maybeSpace = index + 1 === self.length ? '' : ' ' | ||
|
||
accumulator += `${ | ||
messagePrefix ?? | ||
`For query ${parameterWithInflection( | ||
current.path.length | ||
)} ${current.path.toString()}: ` | ||
}${current.message}.${maybeSpace}` | ||
|
||
return accumulator | ||
}, ``) | ||
|
||
return new createError.BadRequest(errorString) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
export { default } from 'next-auth/middleware' | ||
|
||
export const config = { | ||
matcher: [ | ||
/* | ||
* Require authentication for all request paths except for the ones starting with: | ||
* - installation | ||
* - signin (mEditor's sign in page) | ||
* - api (API routes) | ||
* - _next (NextJS static files) | ||
* - images (/public/images static images) | ||
* - favicon.ico | ||
*/ | ||
'/((?!installation|signin|api|_next|images|favicon.ico).*)', | ||
], | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,9 @@ | ||
import { withApiErrorHandler } from 'lib/with-api-error-handler' | ||
import type { NextApiRequest, NextApiResponse } from 'next' | ||
import createError from 'http-errors' | ||
|
||
export default async function handler(_req: NextApiRequest, res: NextApiResponse) { | ||
// TODO: implement | ||
res.status(501).json({ | ||
message: 'Not Implemented', | ||
}) | ||
const handler = async (req: NextApiRequest, res: NextApiResponse) => { | ||
throw createError.NotImplemented() | ||
} | ||
|
||
export default withApiErrorHandler(handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,19 @@ | ||
import type { NextApiRequest, NextApiResponse } from 'next' | ||
import { setUpNewInstallation } from '../../../../setup/service' | ||
import { apiError } from '../../../../utils/errors' | ||
import { withApiErrorHandler } from 'lib/with-api-error-handler' | ||
import assert from 'assert' | ||
import createError from 'http-errors' | ||
|
||
export default async function handler(req: NextApiRequest, res: NextApiResponse) { | ||
switch (req.method) { | ||
case 'POST': { | ||
const [error] = await setUpNewInstallation(req.body) | ||
const handler = async (req: NextApiRequest, res: NextApiResponse) => { | ||
assert(req.method === 'POST', new createError.MethodNotAllowed()) | ||
|
||
if (!!error) { | ||
return apiError(error, res) | ||
} | ||
const [error] = await setUpNewInstallation(req.body) | ||
|
||
return res.status(204).end() | ||
} | ||
|
||
default: | ||
return res.status(405).end() | ||
if (!!error) { | ||
throw error | ||
} | ||
|
||
return res.status(204).end() | ||
} | ||
|
||
export default withApiErrorHandler(handler) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,13 @@ | ||
import type { NextApiRequest, NextApiResponse } from 'next' | ||
import { apiError } from 'utils/errors' | ||
import getCommentsHandler from '../models/[modelName]/documents/[documentTitle]/comments/' | ||
import { documentSchema } from './_schemas' | ||
import { withApiErrorHandler } from 'lib/with-api-error-handler' | ||
|
||
export default async function handler(req: NextApiRequest, res: NextApiResponse) { | ||
try { | ||
// replaces query params with params mapped to RESTful names (e.g. "model" -> "modelName", etc.) | ||
req.query = documentSchema.parse(req.query) | ||
const handler = async (req: NextApiRequest, res: NextApiResponse) => { | ||
// replaces query params with params mapped to RESTful names (e.g. "model" -> "modelName", etc.) | ||
req.query = documentSchema.parse(req.query) | ||
|
||
return getCommentsHandler(req, res) | ||
} catch (err) { | ||
return apiError(err, res) | ||
} | ||
return getCommentsHandler(req, res) | ||
} | ||
|
||
export default withApiErrorHandler(handler) |
Oops, something went wrong.