DRY top-level composable #171
-
|
I'm trying to create a top-level function I can use and apply everywhere. The following works for error mapping, but I would also like to wrap the function call in a (Prisma) transaction. Is the following the correct way to create this top-level composable func? How would I accomplish the transaction solution? import type { ParserSchema } from 'composable-functions'
import { applySchema, mapErrors } from 'composable-functions'
import { AlreadyExistsError } from './err'
import { Prisma } from '@prisma/client'
import { arraysEqual } from '~/utils/array-helpers'
export function myApplySchema<ParsedInput, ParsedContext>(
inputSchema?: ParserSchema<ParsedInput>,
contextSchema?: ParserSchema<ParsedContext>,
) {
return function <R, Input extends ParsedInput, Context extends ParsedContext>(
fn: (input: Input, context: Context) => R,
) {
const fnWithMappedErrors = mapErrors(fn, (errors, ...originalArgs) => {
return errors.map((error) => {
... <map error logic here>...
}
return new Error('Internal server error. Please try again later.')
})
})
return applySchema<ParsedInput, ParsedContext>(
inputSchema,
contextSchema,
)(fnWithMappedErrors)
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Hey @dshunfen, I'm glad to know you are doing a more advanced usage of our library!
I'm not very found of Prisma, but my line of though goes like: // I'd create a function to wrap the given function in a transation
async function wrapInTransaction<T>(fn: T): T {
return (...args: Parameters<T>) => await prisma.$transaction(async () => fn(...args))
}
// The error mapper you mentioned
function errorMapper(errors: Error[]): Error[] {
errors.map((error) => {
// ... <map error logic here>...
}
return [new Error('Internal server error. Please try again later.')]
}
// My pure business logic
function myBusinessLogic(someArgs: ArgsType) {}
// Then I'd be able to use the composable primitives as is:
const myFn = mapErrors(wrapInTransation(myBusinessLogic), errorMapper)
const mySaferFn = applySchema(inputSchema, contextSchema)(myFn)Did you get the idea? Does it help at all? |
Beta Was this translation helpful? Give feedback.
Hey @dshunfen, I'm glad to know you are doing a more advanced usage of our library!
I'm not very found of Prisma, but my line of though goes like: