Skip to content
Snippets Groups Projects
Commit f44b2b3f authored by matthiak00's avatar matthiak00
Browse files

Merge branch 'CarloS' into 'master'

Added MongoDB + CRUD REST Interfaces

See merge request swp-unisport/team-nodejs/unisport-backend!4
parents a6dd5894 74658915
No related branches found
No related tags found
No related merge requests found
node_modules
dist
coverage
.vscode
\ No newline at end of file
## INSTALL GUIDE (first setup)
- install node
- npm install -g typescript
- npm link typescript
- npm install express
### INSTALL DATABASE
- npm install body-parser
- npm install mongoose
## FOR ALL DEVS
- `npm install` after pull to load new dependencies
- install MongoDB Community Server
- install MongoCompass
**const uri: string = "mongodb://127.0.0.1:27017/local";**
Shows a link to the MongoDB Database. The name of the database is local. A new Database can be created in MongoCompass.
After this the new Database can be called with the link.
**export const BookSchema = new mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true }
});**
Here a new Collection is created. A Collection is equivalent to a table in a relational database. A Collection groups MongoDB Docoments. In this case the Documente has the fields title, author.
**const Book = mongoose.model("Book", BookSchema);**
Here we set the name of the Collection.
**Book.findById
Book.find
Book.deleteOne**
Now we can apply typical predefined CRUD methods on const Book.
This diff is collapsed.
......@@ -8,7 +8,8 @@
"build": "tsc",
"lint": "eslint . --ext .ts",
"lint-and-fix": "eslint . --ext .ts --fix",
"prettier-check": "prettier --check .",
"prettier-check": "prettier --ignore-path .gitignore --check .",
"prettier-write": "prettier --ignore-path .gitignore --write .",
"test": "jest --coverage"
},
"repository": {
......@@ -18,7 +19,7 @@
"author": "FU Berlin",
"license": "ISC",
"devDependencies": {
"@types/express": "4.16.1",
"@types/express": "^4.17.11",
"@types/jest": "^26.0.22",
"@types/node": "14.14.41",
"@typescript-eslint/eslint-plugin": "^4.22.0",
......@@ -32,9 +33,11 @@
"prettier": "2.2.1",
"ts-jest": "^26.5.5",
"ts-node": "^9.1.1",
"ts-node-dev": "^1.1.6",
"typescript": "4.2.4"
},
"dependencies": {
"express": "4.16.4"
"express": "4.16.4",
"mongoose": "^5.12.7"
}
}
import express from 'express'
import express, { Request, Response } from 'express'
import * as bookController from './controllers/bookController'
import { connectMongoDB } from './database'
// Our Express APP config
const app = express()
const port = 5000
app.set('port', 5000)
app.use(express.urlencoded({ extended: false })) // Parses urlencoded bodies
app.use(express.json()) // Send JSON responses
app.get('/', (req, res) => {
res.send('The sedulous hyena ate the antelope!')
})
//dfdsd
app.listen(port, () => {
console.log(`localhost:server is listening on ${port}`)
// API Endpoints
app.get('/books', bookController.allBooks)
app.get('/book/:id', bookController.getBook)
app.post('/book', bookController.addBook)
app.put('/book/:id', bookController.updateBook)
app.delete('/book/:id', bookController.deleteBook)
async function startExpress(): Promise<void> {
return new Promise((resolve, reject) => {
app.listen(app.get('port'), () => {
console.log(
'App is running on http://localhost:%d',
app.get('port')
)
resolve()
}).on('error', reject)
})
}
// main startup
;(async () => {
await Promise.all([startExpress(), connectMongoDB()])
console.log('server running and database connected')
})()
import mongoose from 'mongoose'
export interface IBook extends mongoose.Document {
title: string
author: string
}
// Note the capitalized `String`: those are js classes, not typescript types!
export const BookSchema = new mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true }
})
export const BookModel = mongoose.model('Book', BookSchema)
import { Request, Response } from 'express'
import { BookModel } from '../book'
export let allBooks = (req: Request, res: Response) => {
let books = BookModel.find((err: any, books: any) => {
if (err) {
res.send('Error!')
} else {
res.send(books)
}
})
}
export let getBook = (req: Request, res: Response) => {
let book = BookModel.findById(req.params.id, (err: any, book: any) => {
if (err) {
res.send(err)
} else {
res.send(book)
}
})
}
export let deleteBook = (req: Request, res: Response) => {
let book = BookModel.deleteOne({ _id: req.params.id }, (err: any) => {
if (err) {
res.send(err)
} else {
res.send('Successfully Deleted Book')
}
})
}
export let updateBook = (req: Request, res: Response) => {
console.log(req.body)
let book = BookModel.findByIdAndUpdate(
req.params.id,
req.body,
(err: any, book: any) => {
if (err) {
res.send(err)
} else {
res.send('Successfully updated book!')
}
}
)
}
export let addBook = (req: Request, res: Response) => {
var book = new BookModel(req.body)
book.save((err: any) => {
if (err) {
res.send(err)
} else {
res.send(book)
}
})
}
import mongoose from 'mongoose'
const uri: string =
process.env.NODE_ENV === 'production'
? 'TODO: enter prod url'
: 'mongodb://127.0.0.1:27017/local'
export async function connectMongoDB(): Promise<typeof mongoose> {
return mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment