Skip to content

Commit

Permalink
chore: use assert
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon Carlson committed Jan 2, 2025
1 parent 24d7c0f commit 6945a5c
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 66 deletions.
63 changes: 28 additions & 35 deletions packages/app/documents/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,11 +206,12 @@ export async function getDocument(
user?.uid
)

if (!document) {
throw new createError.NotFound(
assert(
document,
new createError.NotFound(
`Requested document, ${documentTitle}, in model, ${modelName}, was not found`
)
}
)

return [null, document]
} catch (error) {
Expand Down Expand Up @@ -359,9 +360,7 @@ export async function cloneDocument(
user: User
): Promise<ErrorData<Document>> {
try {
if (!user) {
throw new createError.Unauthorized('User is not authenticated')
}
assert(user, new createError.Unauthorized('User is not authenticated'))

const documentsDb = await getDocumentsDb()

Expand Down Expand Up @@ -392,11 +391,12 @@ export async function cloneDocument(
titleProperty
)

if (newDocumentAlreadyExists) {
throw new createError.BadRequest(
assert(
!newDocumentAlreadyExists,
new createError.BadRequest(
`A document already exists with the title: '${newDocument[titleProperty]}'`
)
}
)

return createDocument(newDocument, modelName, user)
} catch (error) {
Expand Down Expand Up @@ -471,9 +471,7 @@ export async function patchDocument(
// apply JSON Patch operations to the document
const [patchErrors, patchedDocument] = jsonPatch(existingDocument, operations)

if (patchErrors) {
throw new createError.BadRequest(patchErrors.message)
}
assert(!patchErrors, new createError.BadRequest(patchErrors.message))

// all operations successfully made, save to db as a new document
return await createDocument(patchedDocument, modelName, user)
Expand Down Expand Up @@ -503,13 +501,8 @@ export async function changeDocumentState(
}
): Promise<ErrorData<Document>> {
try {
if (!newState) {
throw new createError.BadRequest('No state provided')
}

if (!user) {
throw new createError.Unauthorized('User is not logged in')
}
assert(newState, new createError.BadRequest('No state provided'))
assert(user, new createError.Unauthorized('User is not logged in'))

const documentsDb = await getDocumentsDb()
const [modelError, model] = await getModelWithWorkflow(modelName)
Expand Down Expand Up @@ -703,33 +696,33 @@ export async function constructNewDocumentState(
newState
)

//! can't transition to a state the document is already in
if (newState === document['x-meditor'].state) {
throw new createError.BadRequest(
assert(
newState !== document['x-meditor'].state,
new createError.BadRequest(
`Cannot transition to state [${newState}] as the document is in this state already`
)
}
)

//! can't transition to a state that isn't in the workflow
if (targetStates.indexOf(newState) < 0) {
throw new createError.BadRequest(
assert(
targetStates.indexOf(newState) >= 0,
new createError.BadRequest(
`Cannot transition to state [${newState}] as it is not a valid state in the workflow`
)
}
)

//! can't transition to a state the user does not have permission to transition to
if (document['x-meditor'].targetStates.indexOf(newState) < 0) {
throw new createError.BadRequest(
assert(
document['x-meditor'].targetStates.indexOf(newState) >= 0,
new createError.BadRequest(
`User does not have the permissions to transition to state ${newState}.`
)
}
)

//! can't transition if the workflow has two edges with the same source and same target (how do we know which edge to follow?)
if (matchingEdges.length !== 1) {
throw new createError.InternalServerError(
assert(
matchingEdges.length === 1,
new createError.InternalServerError(
`Workflow, ${model.workflow.name}, is misconfigured! There are duplicate edges from '${document['x-meditor'].state}' to '${newState}'.`
)
}
)

// create the new document state!
return {
Expand Down
9 changes: 5 additions & 4 deletions packages/app/email-notifications/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from 'assert'
import he from 'he'
import log from '../lib/log'
import mustache from 'mustache'
Expand Down Expand Up @@ -37,10 +38,10 @@ export async function constructEmailMessageForStateChange(
emailToUsers
)

if (!emailToUsers.length && !emailCcUsers.length) {
// need at least one user to notify!
throw new Error('Could not find users to notify of the state change')
}
assert(
emailToUsers.length || emailCcUsers.length,
new Error('Could not find users to notify of the state change')
)

const targetNodes = getNodesFromEdges(model.workflow.currentEdges)

Expand Down
17 changes: 9 additions & 8 deletions packages/app/macros/service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from 'assert'
import cloneDeep from 'lodash.clonedeep'
import createError from 'http-errors'
import log from '../lib/log'
Expand Down Expand Up @@ -27,19 +28,19 @@ async function runModelTemplates(
const [macroName, macroArgument] = template.macro.split(/\s+/)
const macroService = macros.get(macroName)

if (!macroService) {
throw new createError.BadRequest(
`Macro, ${macroName}, not supported.`
)
}
assert(
macroService,
new createError.BadRequest(`Macro, ${macroName}, not supported.`)
)

const [error, filledTemplate] = await macroService(macroArgument)

if (error) {
throw new createError.InternalServerError(
assert(
!error,
new createError.InternalServerError(
`Template macro ${macroName} did not run.`
)
}
)

template.result = filledTemplate

Expand Down
7 changes: 4 additions & 3 deletions packages/app/pages/api/auth/netrc-callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,10 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
},
})

if (!userResult.ok) {
throw new createError.Unauthorized('Failed to retrieve user information')
}
assert(
userResult.ok,
new createError.Unauthorized('Failed to retrieve user information')
)

const userInfo = await userResult.json()
const maxAge = 30 * 24 * 60 * 60 // 30 days
Expand Down
17 changes: 8 additions & 9 deletions packages/app/pages/api/legacy-endpoints/putDocument.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import assert from 'assert'
import createError from 'http-errors'
import { withApiErrorHandler } from 'lib/with-api-error-handler'
import type { NextApiRequest, NextApiResponse } from 'next'
import putDocumentHandler from '../models/[modelName]/documents/'
import { withApiErrorHandler } from 'lib/with-api-error-handler'
import createError from 'http-errors'
import assert from 'assert'

// our new API supports uploading a document as JSON
// however the legacy API only supported file based uploads, which are difficult to use
Expand All @@ -13,15 +13,14 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
//! Step 1: Extract the boundary from the Content-Type header
const contentType = req.headers['content-type']

if (!contentType?.startsWith('multipart/form-data')) {
throw new createError.BadRequest('Invalid content type')
}
assert(
contentType?.startsWith('multipart/form-data'),
new createError.BadRequest('Invalid content type')
)

const boundary = contentType.split('boundary=')[1]

if (!boundary) {
throw new createError.BadRequest('Boundary not found')
}
assert(boundary, new createError.BadRequest('Boundary not found'))

//! Step 2: Split the raw data into parts
const parts = req.body.toString().split(`--${boundary}`)
Expand Down
10 changes: 6 additions & 4 deletions packages/app/pages/signin.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from 'assert'
import Button from 'react-bootstrap/Button'
import Dashboard, { sortModelsIntoCategories } from './index'
import styles from './signin.module.css'
Expand Down Expand Up @@ -102,10 +103,11 @@ export async function getServerSideProps(ctx: GetServerSidePropsContext) {

const providers = await getProviders()

if (!Object.keys(providers).length) {
//! Fatal error that only occurs if mEditor is misconfigured (no provider ENV variables setup)
throw new Error('Failed to retrieve authentication providers')
}
//! Fatal error that only occurs if mEditor is misconfigured (no provider ENV variables setup)
assert(
Object.keys(providers).length,
new Error('Failed to retrieve authentication providers')
)

const modelCategories = sortModelsIntoCategories(models)

Expand Down
5 changes: 2 additions & 3 deletions packages/app/webhooks/service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import createError from 'http-errors'
import log from '../lib/log'
import { assert } from 'console'
import { parseResponse } from '../utils/api'
import { parseZodAsErrorData } from '../utils/errors'
import { safeParseJSON } from '../utils/json'
Expand Down Expand Up @@ -63,9 +64,7 @@ async function invokeWebhook(
body: JSON.stringify(payload),
})

if (!response.ok) {
throw new createError(response.status, response.statusText)
}
assert(response.ok, new createError(response.status, response.statusText))

return [null, await parseResponse(response)]
} catch (error) {
Expand Down

0 comments on commit 6945a5c

Please sign in to comment.