-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
93 lines (83 loc) · 2.55 KB
/
app.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
import express from 'express';
import mongoose from 'mongoose';
import blogpost from './server/routes/blogpost.js';
import questroute from './server/routes/question.js';
import commentroute from './server/routes/blog-comment';
import signuproute from './server/routes/user.js';
import * as bodyParser from 'body-parser';
import dotenv from 'dotenv';
import morgan from 'morgan';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
dotenv.config();
const app = express();
// connection to mango db to an api
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Robert brand API documentation',
version: '0.1.0',
description:
'This a route endpoint that documented my APi with Swagger',
contact: {
name: 'Robert Niyitanga',
url: 'https://github.com/NIRoberto/myband',
email: '[email protected]',
},
},
servers: [
{
url: 'http://my2api.herokuapp.com/',
},
],
produces: ['application/json'],
},
apis: ['../server/routes/*.js'],
};
const specs = swaggerJsdoc(options);
app.use(
'/myband/documentation/',
swaggerUi.serve,
swaggerUi.setup(specs, { explorer: true }),
);
const mangoDB = `mongodb+srv://${process.env.dbuser}:${process.env.dbpass}@blog-db.bj3ci.mongodb.net/${process.env.dbname}?retryWrites=true&w=majority`
mongoose.connect(mangoDB, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
const db = mongoose.connection;
db.on('open', () => {
console.log("db connected")
})
db.on('error', () => {
console.log("db connected falied");
})
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', "Origin,X-Requested-Width,Content-Type,Accept,auth-token");
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods','PUT,POST,GET,PATCH,DELETE')
return res.status(200).json({});
}
next();
})
app.get('/', (req, res) => {
res.status(200).json({
message: "Welcome to my blog's backend API"
});
});
app.use('/api/v1', blogpost);
app.use('/api/v1', questroute);
app.use('/api/v1', signuproute);
app.use('/api/v1', commentroute);
app.use((req, res, next) => {
res.status(404).json({
Error: "invalid url"
})
})
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`app is listening to localhost:${port}`)
})
export default app;