-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.js
More file actions
81 lines (70 loc) · 1.88 KB
/
app.js
File metadata and controls
81 lines (70 loc) · 1.88 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
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const http = require("http");
const openapiValidator = require("express-openapi-validator");
const app = express();
app.use(express.text());
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
const spec = path.join(__dirname, "openapi.yaml");
app.use("/spec", express.static(spec));
// 1. Install the OpenApiValidator on your express app
app.use(
openapiValidator.middleware({
apiSpec: "./openapi.yaml",
})
);
// 2. Add routes
app.get("/v1/pets", function (req, res, next) {
res.json([
{ id: 1, name: "max" },
{ id: 2, name: "mini" },
]);
});
app.post("/v1/pets", function (req, res, next) {
res.json({ name: "sparky" });
});
app.get("/v1/pets/:id", function (req, res, next) {
res.json({ id: req.params.id, name: "sparky" });
});
// 2a. Add a route upload file(s)
app.post("/v1/pets/:id/photos", function (req, res, next) {
// DO something with the file
// files are found in req.files
// non file multipar params are in req.body['my-param']
console.log(req.files);
res.json({
files_metadata: req.files.map((f) => ({
originalname: f.originalname,
encoding: f.encoding,
mimetype: f.mimetype,
// Buffer of file conents
// buffer: f.buffer,
})),
});
});
// 3. Create a custom error handler
app.use((err, req, res, next) => {
// format error
if (!err.status && !err.errors) {
res.status(500).json({
errors: [
{
message: err.message,
},
],
});
} else {
res.status(err.status).json({
message: err.message,
errors: err.errors,
});
}
});
const server = http.createServer(app);
server.listen(3000);
console.log("Listening on port 3000");
module.exports = app;