DavidHancu/prisma-util

Middleware Context API - Accepted Proposal

Closed this issue · 1 comments

Scope

The aim of this proposal is to provide a sneak-peek for the new feature that will be added to Prisma Util v2.0. In this issue, I'll be outlining the process of how Middleware Context can be used for passing down metadata to middleware.

Introduction

This feature will be released under the middlewareContext flag and will require manual activation. Because this feature uses Project Toolchain's Generation API, it will create the typings necessary for configuring context.

Code Example

prisma.user.findMany({
    where: {
        name: "David"
    },
    // The new Context API
    context: {
        anyKey: "anyValue",
        anotherKey: 2
    }
});

Then, in your middleware:

const middleware = async (params, next) => {
    if(params.args.context && params.args.context.anotherKey == 2)
    {
        // do something
    }
    return next(params);
}

Middleware

This feature makes use of Project Toolchain's Middleware API and defines a middleware called contextRemover. To use it, you have to import it like this and add it to your Prisma middleware chain:

import contextRemover from "prisma-util/toolchain/middleware/middlewareContext";
prisma.$use(contextRemover(prisma));

And that's it! Now everything will function correctly whenever you create a new model.

Caveat

This context remover middleware must be the last one in the chain, otherwise you'll be removing the context from further middleware. This must be done to ensure that the context parameter isn't sent to Prisma.

Feature implemented.