访问 PrismaClient 实例在多个文件中

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

Access PrismaClient instance in multiple files

问题

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

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

  1. import { PrismaClient } from '@prisma/client';
  2. const prisma = new PrismaClient();

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

  1. export const createUser: RequestHandler = async (req, res, next) => {
  2. try {
  3. const newUser = await prisma.user.create({
  4. data: {
  5. username: req.body.username,
  6. email: req.body.email,
  7. password: req.body.password,
  8. },
  9. });
  10. res.status(200).json(newUser);
  11. } catch (error) {
  12. next(error);
  13. }
  14. }
  15. export const getUsers: RequestHandler = async (req, res, next) => {
  16. try {
  17. const users = await prisma.user.findMany();
  18. res.status(200).json(users);
  19. } catch (error) {
  20. next(error);
  21. }
  22. }
  23. export const getUser: RequestHandler = async (req, res, next) => {
  24. try {
  25. const userId = parseInt(req.params.userId, 10);
  26. const user = await prisma.user.findUnique({
  27. where: {
  28. id: userId,
  29. },
  30. });
  31. if (!user) {
  32. return res.status(404).json({ error: 'User not found' });
  33. }
  34. res.status(200).json(user);
  35. } catch (error) {
  36. next(error);
  37. }
  38. }

这样,您可以在 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

  1. import express from "express";
  2. import { PrismaClient } from '@prisma/client';
  3. import userRoutes from "./routes/users";
  4. const app = express();
  5. // best not to have multiple instances of PrismaClient
  6. export const prisma = new PrismaClient();
  7. app.get("/", (req, res) => {
  8. res.send("helloBAA")
  9. })
  10. // routes
  11. app.use('/api/users', userRoutes)
  12. app.listen(3500, () => {
  13. console.log("listening on port 3500")
  14. })

routes/users.ts

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

controllers/users.ts

  1. import { RequestHandler } from 'express';
  2. // import prisma from './index.ts';
  3. import dotenv from "dotenv"
  4. import axios from 'axios';
  5. export const createUser:RequestHandler = async (req, res, next) => {
  6. let newObj = {
  7. username: req.body.username,
  8. email: req.body.email,
  9. password: req.body.password
  10. }
  11. res.status(200).json({ "test": "createUser" });
  12. }
  13. export const getUsers: RequestHandler = async (req, res, next) => {
  14. res.status(200).json({ "test": "getUsers" });
  15. }
  16. export const getUser: RequestHandler = async (req, res, next) => {
  17. res.status(200).json({ "test": "getUser" });
  18. }

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 文件

  1. const { PrismaClient } = require("@prisma/client");
  2. const prismaInstance = new PrismaClient();
  3. module.exports = prismaInstance;

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

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

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

  1. 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

  1. const { PrismaClient } = require("@prisma/client");
  2. const prismaInstance = new PrismaClient();
  3. module.exports = prisma;

import the file in the index.ts like this:

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

Import the file from index.ts to required files:

  1. 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:

确定