#Reusing parameter validation

1 messages · Page 1 of 1 (latest)

arctic kestrel
#

I find myself doing this a lot in my action (where the variables are $id and $subId:

    if (!params.id) {
        throw new Response('Not Found', { status: 404 });
    }
    const id = parseInt(params.id, 10);

    const entity = await findById(id);
    if (!entity) {
        throw new Response('Not Found', { status: 404 });
    }

    if (!params.subId) {
        throw new Response('Not Found', { status: 404 });
    }
    const subId = parseInt(params.subId, 10);

    const subEntity = await findBySubId(subId);
    if (!subId) {
        throw new Response('Not Found', { status: 404 });
    }

Any idea how to reduce this boilerplate?

worldly mesa
#
function assertOrThrowResponse<T>(thing: T): asserts thing is NonNullable<T> {
  if (!thing) throw new Response('Not Found', {status: 404})
}```