Using zod along with Prisma to verify user input: A step-by-step guide

Struggling with integrating Zod and Prisma for validation in my project

In my user.model.ts file, I have set up Zod validations as follows:

//user.mode.ts file

const userSchema = z.object({
  username: z.string({
    required_error: "Username field is required",
  }),
  email: z
    .string({
      required_error: "Email field is required",
      invalid_type_error: "This field must be in email format",
    })
    .email(),
  password: z
    .string({
      required_error: "Password field is required",
    })
    .min(6, "Password must be at least 6 characters"),

});

export type UserModel = z.infer<typeof userSchema>;

In my user.service.ts file, there is a function attempting to utilize the validation logic from user.model.ts. Unsure if this implementation is correct.

//user.service.ts file

export const createUser = async (
  username: string,
  email: string,
  password: string
) => {
  const user: UserModel = await prisma.user.create({
    data: {
      username: username,
      email: email,
      password: password,
    },
  });
  return user;
};

The following snippet shows how it appears in the authController.ts file:

//authController.ts file

export const signUpLogic = async (req: Request, res: Response) => {
  const { username, email, password } = req.body;
  try {
    const hashedPassword = await bcrypt.hash(password, 10);
    //
    createUser(username, email, String(hashedPassword));
    //

  } catch (err) {
    if (err instanceof PrismaClientKnownRequestError) {
      if (err.code === "P2002") {
        res.json({ message: "email already taken" });
      }
    }
  }
};

However, upon running the code to test the validations, an unexpected Prisma error is thrown in the terminal instead of being handled by the catch block as intended. The validations also do not seem to be functioning properly, allowing incorrect email formats to pass through.

https://i.sstatic.net/srtZa.png

Answer №1

Don't forget to include the await keyword within the signUpLogic function.

The validations are not functioning correctly as I am still able to input an incorrect email format into the email field.

Make sure to utilize zod for data parsing.

You can implement the following code snippets:

export const createUser = async ({ 
  username,
  email,
  password,
}: UserModel) => {
  const user: UserModel = await prisma.user.create({
    data: {
      username,
      email,
      password,
    },
  });
  return user;
};
export const signUpLogic = async (req: Request, res: Response) => {
  const { username, email, password } = req.body;
  try {
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const result = userSchema.safeParse({ username, email, password: String(hashedPassword)});

    if(result.success) {
      await createUser(result.data);
    } else {
      // handle wrong parsing result
    }
  } catch (err) {
    if (err instanceof PrismaClientKnownRequestError) {
      if (err.code === "P2002") {
        res.json({ message: "email already taken" });
      }
    }
  }
};

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

React 18 update causes malfunctioning of react-switch-selector component

I'm facing an issue where the component is not rendering. I attempted to start a new project but it still didn't work. Is there a solution to fix this problem or should I just wait for an update from the original repository? Encountered Error: ...

Solving the Path Dilemma in TypeScript Functions within the Firebase Environment

My Firebase project utilizes TypeScript functions with the following directory structure: - functions - src - index.ts - shared - other.ts - tsconfig.json - package.json Within my tsconfig.json file, the configuration is as follows: { &q ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

Is there a way to queue request calls so they wait until the previous one is done before completing?

Trying to send an array of items to the server, but struggling with iterating through them correctly. Here's what I have so far: var i = 0; while (i < numOfItems) { var item = items[i]; var a; ...

Error in Node.js: Trying to access the 'body' property of an undefined variable

While working on a project for a Udacity course, I encountered a stumbling block. The issue revolves around capturing user input from a form and making a post request to return a javascript object. However, when attempting to run the server with node js, I ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

The compatibility between Typescript methods and event handlers is lacking

Consider this basic TypeScript script class foo { v: number = 1; public bar() { console.log(this.v); } } var a = new foo(); var b = new foo(); document.getElementById('test').addEventListener("click", a.bar); document.getE ...

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date? let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + currentSelection.startTimeAMPM; let endTime = currentSelection.stopTimeHr + ":" + currentSele ...

Trouble accessing MongoDB through Mlab - Encounter with MongoError: Authentication unsuccessful

I am currently working on building a basic server using nodejs, expressJs, and mongodb Below is my server.js file: const express = require('express'); const MongoClient = require('mongodb').MongoClient; const bodyParser ...

Navigating to URL with Query String correctly using Express

Below is the code I currently have: app.get('/', function (req, res) { req.query.searchQuery = 'test2' res.redirect('/search'); }); app.get('/search/', function (req, res) { var searchQuery = req.query.search ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

Weaving together threaded comments and backboneJS

Presently, I am working on developing a blog application using nodejs/expressjs and mongoDB (+mongoose) as the database. The progress has been smooth so far, but now I am aiming to incorporate nested/threaded comments. After researching different methods ...

Despite the updates, Express JS PUT request does not successfully save changes

Currently, I have an Express JS application where I am attempting to update an existing user's name using the PUT method. The schema I am working with is a nested array and is structured like this: https://i.sstatic.net/WDIse.png The code snippet I ...

What is the best location to store custom Handlebars helpers within an Express application?

Currently, I am delving into the realm of Node.js and diving into an application with Express + Handlebars. I have reached a part where I must create my own helper for the Handelbars view engine. After defining my helper using the registerHelper() method ...

Uncertainty regarding API endpoints in a React project

I am currently in the process of building a comprehensive MERN app that allows users to submit reviews. However, I have encountered some confusion regarding routing and API endpoints. Specifically, when attempting to view my AddReview component in the brow ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...

Typescript Vue Plugin

I am currently working on developing a Vue logger plugin export default new (class CustomLogger { public install(Vue: any) { Vue.prototype.$log = this; } error(text: string) { console.log(text) } })(); This code is located in main.ts f ...

Is there a way to simultaneously query two values in mongoose?

I am currently creating a buildQuery function to extract posts for a social media feed. When users create a post, their affiliated university is stored in the post as university. They can also opt to limit visibility to only students from the same univers ...