-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnoteController.js
130 lines (101 loc) · 2.3 KB
/
noteController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import { prisma } from "../db.js"
const getNotes = async (req,res) => {
try {
const notes = await prisma.note.findMany({
where: {
userId: req.user.id
}
})
res.json(notes)
} catch (error) {
console.log(error)
return res.status(500).json({error: error.message})
}
}
const getNoteById = async (req,res) => {
try {
const { id } = req.params
const note = await prisma.note.findFirst({
where: {
id: parseInt(id),
userId: req.user.id
}
})
if (!note) {
return res.status(404).json({error:'note not found'})
}
res.send(note)
} catch (error) {
res.status(500).json({error: error.message})
console.log(error.message)
}
}
const createNote = async (req,res) => {
try {
const { title, content, color } = req.body
const newNote = await prisma.note.create({
data: {
title: title,
content: content,
color: color,
user:{
connect: {
id: req.user.id
}
}
}
})
if (!newNote) {
return res.status(500).json({error:'error trying to create note'})
}
res.json(newNote)
} catch (error) {
res.status(500).json({error: error})
console.log(error)
}
}
const editNote = async (req,res) => {
try {
const { id } = req.params
const editData = req.body
const editedNote = await prisma.note.update({
where: {
id: parseInt(id),
userId: req.user.id
},
data: editData
})
res.json(editedNote)
} catch (error) {
if(error.code === 'P2025'){ // record to update not found
console.log(error.meta)
return res.status(404).json({error:'note to update not found'})
}
res.status(500).json(error.message)
}
}
const deleteNote = async (req,res) => {
try {
const { id } = req.params
const deletedNote = await prisma.note.delete({
where: {
id: parseInt(id),
userId: req.user.id
}
})
res.json(deletedNote)
} catch (error) {
if (error.code === 'P2025') {
return res.status(404).json({error: error.meta.cause})
}
res.status(500).json({error: error})
console.log(error)
}
}
export {
getNotes,
getNoteById,
createNote,
editNote,
deleteNote
}