typescriptdjango-modelsprismaplumatic-schema

Prisma create custom function in schema


I have a mongo collection where there is a field called amount. What I want is whenever I ask for the amount I want it divided by 100. The Django equivalent of it is a custom function inside the model. I have done the same like this

class Book(models.Model):
    title = models.CharField(...)
    price = models.IntegerField()

    
    def get_price(self):
        return self.price // 100

What is the prisma equivalent of this in typescript?

I tried the same thing in django and it worked fine. What I want is how to implement it in Prisma setup in nestJs.

class Book(models.Model):
    title = models.CharField(...)
    price = models.IntegerField()

    
    def get_price(self):
        return self.price // 100

Solution

  • I found the solution in the prisma docs. I have to use custom field to query results.

    it can be used as

    const xprisma = prisma.$extends({
      result: {
        user: {
          fullName: {
            // the dependencies
            needs: { firstName: true, lastName: true },
            compute(user) {
              // the computation logic
              return `${user.firstName} ${user.lastName}`
            },
          },
        },
      },
    })
    
    const user = await xprisma.user.findFirst()
    
    // return the user's full name, such as "John Doe"
    console.log(user.fullName)
    
    

    Here is the link to the docs.