Skip to content

Commit 18e65eb

Browse files
committed
Add seeds and DELETE routes
1 parent e7ab38b commit 18e65eb

File tree

2 files changed

+47
-12
lines changed

2 files changed

+47
-12
lines changed

src/index.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,35 @@ app.get("/", (req, res) => {
3737
// Re-initialize your database on every Express server start
3838
const eraseDatabaseOnSync = true;
3939
sequelize.sync({ force: eraseDatabaseOnSync }).then(async () => {
40+
if (eraseDatabaseOnSync) {
41+
seedDatabaseWithResources();
42+
}
43+
4044
app.listen(process.env.PORT, () => {
4145
console.log(`Listening on port ${process.env.PORT}`);
4246
});
4347
});
48+
49+
const seedDatabaseWithResources = async () => {
50+
await models.Resource.create({
51+
title: "resource-title",
52+
description: "resource-description",
53+
url: "www.some-resource-url.com",
54+
referrer: "resource-referrer",
55+
credit: "resource-person",
56+
published: Date.now(),
57+
created: Date.now(),
58+
type: "resource-type"
59+
});
60+
61+
await models.Resource.create({
62+
title: "another-resource-title",
63+
description: "another-resource-description",
64+
url: "www.some-resource-url.com",
65+
referrer: "resource-referrer",
66+
credit: "resource-person",
67+
published: Date.now(),
68+
created: Date.now(),
69+
type: "resource-type"
70+
});
71+
};

src/routes/resource.js

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,37 @@
1-
import { uuidv4 as uuid } from "uuid/v4";
21
import { Router } from "express";
32

43
const router = Router();
54

6-
router.get("/", (req, res) => {
7-
return res.send(Object.values(req.context.models.resources));
5+
router.get("/", async (req, res) => {
6+
const resources = await req.context.models.Resource.findAll();
7+
return res.send(resources);
88
});
99

10-
router.get("/:resourceId", (req, res) => {
11-
return res.send(req.context.models.resources[req.params.resourceId]);
10+
router.get("/:resourceId", async (req, res) => {
11+
const resource = await req.context.models.Resource.findByPk(
12+
req.params.resourceId
13+
);
14+
return res.send(resource);
1215
});
1316

14-
router.post("/", (req, res) => {
15-
const id = uuid();
16-
const resource = {
17-
id,
17+
router.post("/", async (req, res) => {
18+
const resource = await req.context.models.Resource.create({
1819
title: req.body.title,
1920
description: req.body.description,
2021
url: req.body.url,
2122
published: Date.now(),
2223
created: Date.now()
23-
};
24-
25-
// TODO: Sequelize
24+
});
2625

2726
return res.send(resource);
2827
});
2928

29+
router.delete("/:resourceId", async (req, res) => {
30+
const result = await req.context.models.Resource.destroy({
31+
where: { id: req.params.resourceId }
32+
});
33+
34+
return res.send(true);
35+
});
36+
3037
export default router;

0 commit comments

Comments
 (0)