DavidHancu / prisma-util

Merge multiple Prisma schema files, model inheritance, resolving name conflicts and timings reports, all in a simple tool.
Apache License 2.0
40 stars 1 forks source link

Custom functions for @default - Accepted Proposal #5

Closed DavidHancu closed 1 year ago

DavidHancu commented 1 year ago

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 defining a function and how the configuration will look like, so you can make preparations in advance.

Introduction

This feature will be released under the customAttributeFunctions flag and will require manual activation.

Configuration

To set a default function for a field, we can just do this:

function generateDefault(dmmf) {
    // Generate your default value based on the DMMF data of this field
    const defaultValue = "";
    return defaultValue;
}
export default {
    // Other configuration values
    defaultFunctions: {
        "path/to/file:ModelName.field": generateDefault
    }
}

The function will then be grabbed by Prisma Util and added to a function map. To copy the function over, Prisma Util will use .toString() on the provided function and wrap the code in another function, as such:

const columnMappings = {
    "ModelName.field": function() {
        const func = function generateDefault(dmmf) {
            // Generate your default value based on the DMMF data of this field
            const defaultValue = "";
            return defaultValue;
        }
        return func;
    }(),
}

Middleware

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

import attributeFunctions from "prisma-util/toolchain/middleware/customAttributeFunctions";
prisma.$use(attributeFunctions(prisma));

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

Final Words

Please let us know if this is suitable for you and if you would like any changes to be made.

DavidHancu commented 1 year ago

Feature implemented.