forked from Technigo/js-project-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (56 loc) · 1.55 KB
/
server.js
File metadata and controls
67 lines (56 loc) · 1.55 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
import cors from "cors"
import express from "express"
import listEndpoints from "express-list-endpoints"
import "dotenv/config"
import mongoose from "mongoose"
import happyData from "./data.json" with { type: "json" }
import happyThoughtsRoutes from "./routes/happyThoughtsRoutes.js"
import userRoutes from "./routes/userRoutes.js"
let data = happyData
const mongoUrl = process.env.MONGO_URL
mongoose.connect(mongoUrl)
// Defines the port the app will run on. Defaults to 8080, but can be overridden
// when starting the server. Example command to overwrite PORT env variable value:
// PORT=9000 npm start
const port = process.env.PORT || 8080
const app = express()
// Add middlewares to enable cors and json body parsing
app.use(cors())
app.use(express.json())
const thoughtsSchema = new mongoose.Schema ({
message: {
type: String,
required: true
},
hearts: {
type: Number
},
createdAt: {
type: Date,
default: Date.now
}
})
const Thought = mongoose.model("Thought", thoughtsSchema)
if (process.env.RESET_DB === "true") {
const seedDataBase = async () => {
await Thought.deleteMany()
data.forEach(thought => {
new Thought(thought).save()
})
}
seedDataBase()
}
// Start defining your routes here
app.get("/", (req, res) => {
const endpoints = listEndpoints(app)
res.json({
message: "Welcome to happy thoughts api",
endpoints: endpoints
})
})
app.use("/happy-thoughts", happyThoughtsRoutes)
app.use("/users", userRoutes)
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})