Skip to content

Instantly share code, notes, and snippets.

@flybayer
Last active January 27, 2021 23:37
Show Gist options
  • Save flybayer/394bf9ce1cf1fb7c6b74866d19d7b38b to your computer and use it in GitHub Desktop.
Save flybayer/394bf9ce1cf1fb7c6b74866d19d7b38b to your computer and use it in GitHub Desktop.
Production Blitz.js Code Before & After New Pipe Utilities
// app/test-results/queries/getTestResult.ts
import { Ctx, NotFoundError } from "blitz"
import db, { Prisma, TestResult as TestResultBase } from "db"
import { ReportData } from "../types"
type GetTestResultInput = {
id: number
}
type TestResult = TestResultBase & {
data: ReportData
}
export default async function getTestResult({ id }: GetTestResultInput, ctx: Ctx) {
ctx.session.$authorize()
let where: Prisma.TestResultWhereInput = { id }
if (!ctx.session.$isAuthorized("admin")) {
where.student = {
organizationId: ctx.session.orgId,
}
}
const testResult = await db.testResult.findFirst({ where })
if (!testResult) throw new NotFoundError()
return testResult as TestResult
}
// app/test-results/queries/getTestResult.ts
import { pipe, NotFoundError } from "blitz"
import db, { TestResult as TestResultBase } from "db"
import { ReportData } from "../types"
import * as z from "zod"
import { authorizeAdminIfNotCurrentOrganization, setDefaultOrganizationId } from "app/core/utils"
const GetTestResult = z.object({
id: z.number(),
organizationId: z.number().optional(),
})
type TestResult = TestResultBase & {
data: ReportData
}
export default pipe.resolver(
pipe.zod(GetTestResult),
pipe.authorize(),
setDefaultOrganizationId,
authorizeAdminIfNotCurrentOrganization,
async ({ id, organizationId }) => {
const testResult = await db.testResult.findFirst({
where: { id, organizationId },
})
if (!testResult) throw new NotFoundError()
return testResult as TestResult
}
)
import { Ctx, pipe } from "blitz"
export const setDefaultOrganizationId = <T extends Record<any, any>>(
input: T,
{ session }: Ctx
): T & { organizationId: number } => ({
...input,
organizationId: input.organizationId ?? session.orgId,
})
export const authorizeAdminIfNotCurrentOrganization = pipe.authorizeIf(
<T extends { organizationId: number }>(input: T, ctx: Ctx) => {
if (!ctx.session.orgId) throw new Error("missing session.orgId")
return input.organizationId !== ctx.session.orgId
},
"admin"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment