-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (64 loc) · 1.72 KB
/
index.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
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
app.use(express.json());
app.get('/', (req, res) => {
res.json({message: 'alive'});
});
app.listen(port, () => {
console.log(`Listening to requests on port ${port}`);
});
app.get('/quotes', async (req, res) => {
const currentPage = req.query.page || 1;
const listPerPage = 5;
const offset = (currentPage - 1) * listPerPage;
const allQuotes = await prisma.quote.findMany({
include: { author: true },
skip: offset,
take: listPerPage,
});
res.json({
data: allQuotes,
meta: {page: currentPage}
});
});
app.post('/quotes', async (req, res) => {
const authorName = req.body.author;
const quote = {
quote: req.body.quote
};
if (!authorName || !quote.quote) {
return res.status(400).json({message: 'Either quote or author is missing'});
}
try {
const message = 'quote created successfully';
const author = await prisma.author.findFirst({
where: { name: authorName }
});
if(!author) {
await prisma.author.create({
data: {
'name': authorName,
Quotes: {
create: quote
}
}
});
console.log('Created author and then the related quote');
return res.json({message});
}
await prisma.quote.create({
data: {
quote: quote.quote,
author: { connect: { name: authorName } }
}
});
console.log('Created quote for an existing author');
return res.json({message});
} catch(e) {
console.error(e);
return res.status(500).json({message: 'something went wrong'});
}
});