访问 PrismaClient 实例在多个文件中

huangapple go评论61阅读模式
英文:

Access PrismaClient instance in multiple files

问题

controllers/users.ts 文件中,您想要在多个文件中访问 PrismaClient 实例,可以通过以下方式解决:

首先,在 controllers/users.ts 文件的顶部,添加以下代码以引入 PrismaClient:

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

const prisma = new PrismaClient();

然后,您可以在 controllers/users.ts 文件的各个函数中使用 prisma 变量来访问 PrismaClient 实例,就像这样:

export const createUser: RequestHandler = async (req, res, next) => {
  try {
    const newUser = await prisma.user.create({
      data: {
        username: req.body.username,
        email: req.body.email,
        password: req.body.password,
      },
    });

    res.status(200).json(newUser);
  } catch (error) {
    next(error);
  }
}

export const getUsers: RequestHandler = async (req, res, next) => {
  try {
    const users = await prisma.user.findMany();
    res.status(200).json(users);
  } catch (error) {
    next(error);
  }
}

export const getUser: RequestHandler = async (req, res, next) => {
  try {
    const userId = parseInt(req.params.userId, 10);
    const user = await prisma.user.findUnique({
      where: {
        id: userId,
      },
    });

    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    res.status(200).json(user);
  } catch (error) {
    next(error);
  }
}

这样,您可以在 controllers/users.ts 文件中的每个函数中共享同一个 PrismaClient 实例,而无需在每个函数中重新创建它。

英文:

I have a node.js/express app with the Prisma ORM. I would like to access my PrismaClient instance in multiple files, not just index.ts.

Tutorials I have seen all only access the PrismaClient instance inside index.ts, which makes that file bloated.

For example, I have folders for routes and controllers. I would like to access the PrismaClient in each of the files within the controllers folder.

Current code:

index.ts


    import express from "express"; 
    import { PrismaClient } from '@prisma/client';
    import userRoutes from "./routes/users";
    
    
    const app = express(); 
    
    // best not to have multiple instances of PrismaClient
    export const prisma = new PrismaClient();
    
    app.get("/", (req, res) => {
        res.send("helloBAA")
    })
    
    // routes 
    app.use('/api/users', userRoutes)
    
    app.listen(3500, () => {
        console.log("listening on port 3500")
    })

routes/users.ts


    import { Router } from 'express'; 
    import { createUser, getUsers, getUser } from '../controllers/users';
    const router = Router(); 
    
    
    // whole route: /api/users...
    router.post('/create', createUser); 
    router.get('/all', getUsers);
    router.get('/:userId', getUser); 
    
    
    export default router; 

controllers/users.ts


    import { RequestHandler } from 'express'; 
    // import prisma from './index.ts';
    import dotenv  from "dotenv"
    import axios from 'axios'; 
    
    
    export const createUser:RequestHandler = async (req, res, next) => {
      let newObj = {
          username: req.body.username,
          email: req.body.email, 
          password: req.body.password
        }   
      
        res.status(200).json({ "test": "createUser" });
    }
    
    export const getUsers: RequestHandler = async (req, res, next) => {
    
      res.status(200).json({ "test": "getUsers" });
    }
    
    export const getUser: RequestHandler = async (req, res, next) => {
    
      res.status(200).json({ "test": "getUser" });
    }

If I try to import prisma from index.ts into controllers/users.ts, I get errors. How should I fix this?

答案1

得分: 1

这是因为存在循环依赖,两个或更多模块直接或间接地相互依赖,形成一个循环。在一个单独的文件中创建一个 prismaClient 实例,并在需要时进行导入。像这样:我有一个 prismaClient.ts 文件

const { PrismaClient } = require("@prisma/client");
const prismaInstance = new PrismaClient();

module.exports = prismaInstance;

在 index.ts 中像这样导入该文件:

const prismaInstance = require("./prismaClient");
export const prisma = prismaInstance;

从 index.ts 导入该文件到需要的文件中:

const prisma = require('./index');
英文:

This is because circular dependency where two or more modules depend on each other directly or indirectly, froming a loop.
Make the prismaClient instance in a separate file and import this whenever required.Like this:I have a prismaClient.ts file

const { PrismaClient } = require("@prisma/client");
const prismaInstance = new PrismaClient();

module.exports = prisma;

import the file in the index.ts like this:

const prismaInstance = require("./prismaClient");
export const prisma = prismaInstance;

Import the file from index.ts to required files:

const prisma = require('./index');

huangapple
  • 本文由 发表于 2023年5月22日 04:56:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定