Is there a way to make PrismaClient return DateTime fields as Unix timestamps rather than JavaScript date objects?

When utilizing the PrismaClient for database interaction, DateTime fields are returned as JavaScript Date objects instead of Unix timestamp numbers. Despite being stored as Unix timestamp numbers in the database itself, I require the dates to be retrieved as Unix timestamps. How can I prevent PrismaClient from unnecessary conversion?

Here is an example of my model:

model Settings {
  id        Int        @id @default(autoincrement())
  updatedAt DateTime   @updatedAt
}

During interaction with the database:

const prisma = new PrismaClient()
const mySettings = await prisma.settings.findFirst()
console.log(mySettings.updatedAt) // An irritating javascript date object >:(

Answer №1

If you are using versions prior to 4.7.0, you can utilize middlewares. On the other hand, starting from version 4.7.0, you have the option to make use of extensions. Here's what is mentioned about Prisma Client extensions:

Prisma Client extensions became Generally Available in versions 4.16.0 and above. They were initially introduced in Preview mode with version 4.7.0. If your current version is earlier than 4.16.0, ensure that you enable the clientExtensions Preview feature flag.

Using Middleware

It's important to note that even with this approach, the type of the result will still remain as Date.

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// Incorrect typings
prisma.$use(async (params, next) => {
  const result = await next(params);
  if (typeof result === "object" && result !== null) {
    for (let [key, value] of Object.entries(result)) {
      if (value instanceof Date) {
        result[key as keyof typeof result] = Math.floor(
          Date.parse(value.toString()) / 1000
        );
      }
    }
    return result;
  } else {
    return result;
  }
});

async function main() {
  const res = await prisma.settings.findUnique({ where: { id: 1 } });
  console.dir(res, { depth: Infinity }); // { id: 1, updatedAt: 1691465195 }
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });

Using Extension

With extensions, there are two options available. You can either modify through query or by result. The former can be applied to specific types of queries or models, while the latter only works for a particular model type but ensures correct typing.

Implementing an extension via query modification -

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// Export this instance for usage purposes
const exPrisma = prisma.$extends({
  // Modify behavior for all queries and models
  // Incorrect typings
  query: {
    $allModels: {
      $allOperations({ args, model, operation, query }) {
        const result = query(args).then((res) => {
          if (typeof res === "object" && res !== null) {
            let modifiedRes = { ...res };
            for (let [key, value] of Object.entries(modifiedRes)) {
              if (value instanceof Date) {
                (modifiedRes[key as keyof typeof modifiedRes] as any) =
                  Math.floor(Date.parse(value.toString()) / 1000);
              }
            }
            return modifiedRes;
          } else {
            return res;
          }
        });
        return result;
      },
    },
  }
});

async function main() {
  const res = await exPrisma.settings.findUnique({ where: { id: 1 } });
  console.dir(res, { depth: Infinity });
}

main()
  .then(async () => {
    await exPrisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await exPrisma.$disconnect();
    process.exit(1);
  });

Applying an extension via result modification -

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

// Export this instance for usage
const exPrisma = prisma.$extends({
  // Specific models with correct typings
  result: {
    settings: {
      withUnixDate: {
        compute(data) {
          return {
            ...data,
            updatedAt: Math.floor(Date.parse(data.updatedAt.toString()) / 1000),
          };
        },
      },
    },
  },
});

async function main() {
  const res = await exPrisma.settings.findUnique({ where: { id: 1 } });
  console.dir(res?.withUnixDate, { depth: Infinity });
}

main()
  .then(async () => {
    await exPrisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await exPrisma.$disconnect();
    process.exit(1);
  });

Choose the method that best suits your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unit testing the error function within the subscribe method in Angular

I've been working on a unit test for the subscribe call, but I'm struggling to cover the error handling aspect of the subscribe method. The handleError function deals with statusCode=403 errors and other status codes. Any assistance would be grea ...

Is emitting a side effect event acceptable within an RxJS pipe?

Currently, I am utilizing RxJS within the context of an Angular application. Within my service, there is functionality to reinitialize the entire application with different settings as needed. @Injectable() class BootstrapService{ public initApplicatio ...

Troubleshooting Internal Server Error on Deployed Next.js Full Stack Application

As a beginner in next.js, I've been encountering difficulties deploying my full stack app. Various platforms like Heroku, Vercel, Netlify, and Nextron all result in the same 500 internal server error. When I switch from "getServerSideProps" to "getSta ...

`Is there a way to repurpose generic type?`

For instance, I have a STRING type that is used in both the test and test2 functions within the test function. My code looks like this: type STRING = string const test = <A = STRING>() => { test2<A>("0") } const test2 = <B& ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

Why is my Vue view not being found by Typescript (or possibly Webpack)?

npx webpack TS2307: Cannot locate module './App.vue' or its corresponding type declarations. I am currently utilizing webpack, vue, and typescript. My webpack configuration is pretty basic. It uses a typescript file as the entry point and gener ...

Setting a blank value or null equivalent to a field: Tips and tricks

Here is the component state that I am working with: interface Person { name: string; surname: string; } interface CompState{ //...fields ... person?: Person; } render() { if(this.state.person){ const comp = <div>{this. ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

Angular 2 and .NET Core 2.0 triggering an endless loop upon page refresh detection

My application, built with dotnet core 2.0 and angular 2, allows me to view member details. The process begins with a list page displaying all the members from a SQL Server database. Each member on the list has a link that leads to an individual details pa ...

What is the best way to sift through slug data?

Struggling to display related posts from the same category in my project using Sanity for slug data. Attempted fetching all data and storing it in the state but unsure how to filter based on the current post's category. I'm thinking about leverag ...

Retrieve an object containing properties specified in the function's parameter list

I am currently working on developing a function that can dynamically create and return an object with properties based on an array of strings provided as parameters. type Foods = 'apple' | 'banana' | 'pear'; function foodObje ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Retrieving information from the Dog API using axios and storing the results in a fresh array

Currently, I am working on a NextJS app using Typescript. My issue lies in the functionality aspect of the application. I am utilizing the Dog API to retrieve all the breeds names and store them in a new array of arrays. Each sub-array contains the breed a ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...

Retrieving routing information from directives within angular2

const APP_ROUTES: RouterConfig = [ { path: 'app/home', component: HomeComponent, data: { name: 'Home' } } ] Assuming the route configuration is set as displayed above, how can one ...

A method to simultaneously retrieve all emitted values from multiple EventEmitters in Angular 7

I am facing a scenario where I have a parent component that consists of multiple child components. Each child component may differ from the others, creating a diverse structure within the parent component. Here's an example: ...

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component: Input.html <form (submit)="getTransactions()"> <div class="form-group"> <label for="exampleInputEmail1"></label> <input type="t ...

Changing the button class during an event in Angular 4

In the process of creating an MCQ test, I am looking to implement a feature where selected button options are highlighted in green upon clicking. While I have successfully implemented this feature using Angular 1, I am facing challenges in converting it to ...