-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
95 lines (78 loc) · 2.23 KB
/
server.js
File metadata and controls
95 lines (78 loc) · 2.23 KB
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
'use strict';
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const authorize = require('./auth/authorize.js');
const PORT = process.env.PORT;
const MONGODB_URL = process.env.MONGODB_URL;
const mongoose = require('mongoose');
const Character = require('./CharacterModel');
app.use(cors());
app.use(express.json());
app.use(authorize);
mongoose.connect(MONGODB_URL);
app.post('/character', async (req, res) => {
try {
const characterData = req.body;
const newCharacter = new Character(characterData);
const savedCharacter = await newCharacter.save();
res.status(201).json(savedCharacter);
} catch (e) {
console.log('error creating new character: ', e);
res.status(500).send(e);
}
});
app.get('/character/:userEmail', async (req, res) => {
// console.log('getting list of characters.')
const { userEmail } = req.params;
// console.log('Yup, its working!');
try {
const characters = await Character.find({ userEmail});
res.json(characters);
} catch (e) {
res.status(500).send(e);
}
});
app.get('/character', async (req, res) => {
// console.log('getting list of characters.')
try {
const characters = await Character.find({ });
res.json(characters);
} catch (e) {
res.status(500).send(e);
}
});
// Update a Character
app.patch('/character/:id', async (req, res) => {
const { id } = req.params;
try {
const updatedCharacter = await CharacterModel.findByIdAndUpdate(id, req.body, { new: true });
if (updatedCharacter) {
res.status(200).json(updatedCharacter);
} else {
res.status(404).send("Character not found");
}
} catch (e) {
// Handle any errors
console.error(e);
res.status(500).send(e);
}
});
// Delete a Character
app.delete('/character/:id', async (req, res) => {
const { id } = req.params;
try {
const deletedCharacter = await Character.findByIdAndDelete(id);
if (deletedCharacter) {
res.status(200).json(deletedCharacter);
} else {
res.status(404).send("Character not found");
}
} catch (e) {
res.status(500).send(e);
}
});
app.listen(PORT, () => {
console.log(`Lorecraft Server v 0.3.1 is running on port ${PORT}`);
});