Задать вопрос
zenithxxl
@zenithxxl
Веб-разработчик

Почему не работает запрос?

Я делаю фитнес-приложение используя Express, Prisma, PostgreSQL. Во время создания "упражнения" всё было хорошо, но скопировав код и переименовав всё с Exercise на Workout(и добавив небольшой функционал) Workout не заработал. Однако создание/получение/удаление упражнений работает.

Ошибка

TypeError: Cannot read properties of undefined (reading 'create')
at file:///C:/Users/kiril/Desktop/HTMLLESSONS/workout...
at asyncUtilWrap (C:\Users\kiril\Desktop\HTMLLESSONS\workout\wa-server\node_modules\express-async-handler\index.js:3:20)
at Layer.handle [as handle_request] (C:\Users\kiril\Desktop\HTMLLESSONS\workout\wa-server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\kiril\Desktop\HTMLLESSONS\workout\wa-server\node_modules\express\lib\router\route.js:144:13)
at file:///C:/Users/kiril/Desktop/HTMLLESSONS/workout...


workout.controller.js
import asyncHandler from 'express-async-handler'

import { prisma } from '../prisma.js'

export const createNewWorkout = asyncHandler(async (req, res) => {
	const { name, exerciseIds } = req.body

	const workout = await prisma.workout.create({
		data: {
			name,
			exercises: {
				connect: exerciseIds.map(id => ({ id: +id }))
			}
		}
	})

	res.json(workout)
})
// @desc    Get workouts
// @route   GET /api/workouts
// @access  Private
export const getWorkouts = asyncHandler(async (req, res) => {
	const workouts = await prisma.workout.findMany({
		orderBy: {
			createdAt: 'desc'
		},
		include: {
			exercises: true
		}
	})

	res.json(workouts)
})


workouts.router.js
import express from 'express'

import { protect } from '../middleware/auth.middleware.js'

import {
	createNewWorkout,
	deleteWorkout,
	getWorkout,
	getWorkouts,
	updateWorkout
} from './workout.controller.js'

const router = express.Router()

router.route('/').post(protect, createNewWorkout).get(protect, getWorkouts)

router
	.route('/:id')
	.get(protect, getWorkout)
	.put(protect, updateWorkout)
	.delete(protect, deleteWorkout)

export default router


prisma.js
import { PrismaClient } from '@prisma/client'

export const prisma = new PrismaClient()


schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  email    String   @unique
  name     String
  password String
  images   String[]
}

model Workout {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  name      String
  exercises Exercise[]
}

model Exercise {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  name     String
  times    Int
  iconPath String @map("icon_path")

  workouts Workout[]
}


server.js Главный файл
import 'colors'
import dotenv from 'dotenv'
import express from 'express'
import morgan from 'morgan'
import path from 'path'

import { errorHandler, notFound } from './app/middleware/error.middleware.js'

import authRoutes from './app/auth/auth.routes.js'
import exerciseRoutes from './app/exercise/exercise.routes.js'
import { prisma } from './app/prisma.js'
import userRoutes from './app/user/user.routes.js'
import workoutRoutes from './app/workout/workout.routes.js'

dotenv.config()

const app = express()

async function main() {
	if (process.env.NODE_ENV === 'development') app.use(morgan('dev'))

	app.use(express.json())

	const __dirname = path.resolve()

	app.use('/uploads', express.static(path.join(__dirname, '/uploads/')))

	app.use('/api/auth', authRoutes)
	app.use('/api/users', userRoutes)
	app.use('/api/exercises', exerciseRoutes)
	app.use('/api/workouts', workoutRoutes)

	app.use(notFound)
	app.use(errorHandler)

	const PORT = process.env.PORT || 5000

	app.listen(
		PORT,
		console.log(
			` Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.blue
				.bold
		)
	)
}

main()
	.then(async () => {
		await prisma.$disconnect()
	})
	.catch(async e => {
		console.error(e)
		await prisma.$disconnect()
		process.exit(1)
	})
  • Вопрос задан
  • 55 просмотров
Подписаться 1 Средний Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы