Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Daniel Monera Postman book service
- //Connections and general lines
- const mongoose = require('mongoose');
- const express = require('express');
- const uniqueValidator = require('mongoose-unique-validator');
- const validate = require('mongoose-validator');
- const bodyParser = require('body-parser');
- const jwt = require('jsonwebtoken');
- const sha256 = require('sha256');
- const fs = require('fs');
- const secretWord = "SecretWord";
- mongoose.Promise = global.Promise;
- mongoose.connect('mongodb://localhost:27017/book-services', {useMongoClient: true});
- //Schemas
- let userSchema = new mongoose.Schema({
- name: {
- type: String,
- required: true,
- minlength: 1,
- trim: true,
- unique: true,
- validate: [
- validate({
- validator : 'isAlphanumeric',
- message : 'caps must be numbers and letters only'
- })
- ]
- //I prefer to use packages, easier and cleaner ;)
- /*validate : [{
- msg : 'only alphanumeric characters',
- validator : function (value) {
- return /^[a-z0-9]+$/i.test(value);
- }
- }]*/
- },
- password: {
- type: String,
- required: true,
- minlength: 4
- }
- });
- let bookSchema = new mongoose.Schema({
- author:{
- type: String,
- required: true,
- trim: true,
- minlength: 4
- },
- title:{
- type: String,
- required: true,
- trime: true,
- minlength: 1
- },
- published:{
- type: Date,
- required: true
- },
- price:{
- type: Number,
- required: true,
- min: 0,
- max: 5000
- },
- image:{
- type: String,
- required: false
- }
- });
- let commentSchema = new mongoose.Schema({
- book:{
- type: mongoose.Schema.Types.ObjectId,
- ref: 'books',
- required: true
- },
- user:{
- type: mongoose.Schema.Types.ObjectId,
- ref: 'users',
- required: true
- },
- text:{
- type: String,
- required:true,
- trim:true,
- minlength: 5
- },
- score:{
- type: Number,
- min: 1,
- max: 5,
- default:3
- }
- });
- let User = mongoose.model('users', userSchema);
- let Book = mongoose.model('books', bookSchema);
- let Comment = mongoose.model('comments', commentSchema);
- //REST service
- let app = express();
- app.use(bodyParser.json());
- //Generate token with the secret word
- let generateToken = login => {
- let token = jwt.sign({login: login}, secretWord,
- {expiresIn:"365 days"});
- return token;
- };
- //Function to validate the token
- let validateToken = token => {
- try {
- let result = jwt.verify(token, secretWord);
- return result;
- } catch (e) {
- }
- }
- //POST /REGISTER Register a new user
- app.post('/register', (req, res) => {
- let newUser = new User({
- name: req.body.name,
- password: sha256(req.body.password) //Encrypt the password with SHA256
- });
- newUser.save().then(result => {
- let data = {error: false, result: result};
- res.send(data);
- }).catch(error => {
- console.log(error);
- let data = {error: true,
- errorMessage:"User couldn't be registered"};
- res.send(data);
- });
- });
- //POST /LOGIN Login with the username using a encrypted password
- app.post('/login', (req, res) => {
- // Get user credentials from the request
- let userClient = {
- name: req.body.name,
- password: req.body.password
- };
- // Look for user in the User collection
- User.find({name: userClient.name,
- password: sha256(userClient.password)})
- .then(data => {
- // User is valid. Generate token
- if (data) {
- let token = generateToken(userClient.name);
- let result = {error: false, token: token};
- res.send(result);
- // User not found. Generate error message
- } else {
- let result = {error: true,
- errorMessage: "Invalid user"};
- res.send(result);
- }
- }).catch (error => {
- // Error searching user. Generate error message
- console.log(error);
- let result = {error: true, errorMessage: "Error validating user"};
- res.send(result);
- });
- });
- //GET /BOOKS Get the complete books array
- app.get('/books', (req, res) => {
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- //If the token is valid we continue with the request
- if (result) {
- Book.find().then(result => {
- res.send(result);
- })
- } else{
- res.sendStatus(401);
- }
- });
- //POST /BOOKS Publicate a new book
- app.post('/books', (req, res)=> {
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- //If the token is valid we continue with the request
- if (result) {
- let imageName = 'img/' + Date.now() + '.jpg';
- let imageJPG = fs.writeFileSync(imageName, Buffer.from(req.body.image, 'base64'));
- let newBook = new Book({
- author: req.body.author,
- title: req.body.title,
- price: req.body.price,
- published: req.body.published,
- image: imageName
- });
- newBook.save().then(result=>{
- let data = {error: false, result: result};
- res.send(data);
- }).catch(error => {
- console.log(error);
- let data = {error: true, errorMessage: "Error adding new book"};
- res.send(data);
- });
- } else{
- res.sendStatus(401);
- }
- });
- //DELETE /BOOKS/:ID Delete the book and his comments.
- app.delete('/books/:id', (req, res) =>{
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- //If the token is valid we continue with the request
- if (result) {
- //Comment.remove({book: request.params.id}).then(() => {
- Book.findByIdAndRemove(req.params.id).then(result => {
- let data = {error: false, result: result};
- res.send(data);
- }).catch(error =>{
- console.log(error);
- let data = {error: true, errorMessage: "Error deleting book"};
- });
- //});
- } else{
- res.sendStatus(401);
- }
- });
- //I don't know how to do it in this way////////////////////////////////////////////////////////////////
- //PUT /BOOKS/:ID Update a current book
- app.put('/books:id', (req, res) =>{
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- //If the token is valid we continue with the request
- if (result) {
- Book.findById(req.params.id).then(book => {
- $set: {
- author: req.body.author,
- title: req.body.title,
- published: req.body.age,
- price: req.body.price,
- image: req.body.image
- }
- book.save().then(book => {
- let data = {error: false, result: result};
- res.send(data);
- }).catch(error => {
- console.log(error);
- let data = {error: true, errorMessage: "Error updating book"};
- });
- }).catch(error => {
- console.log(error);
- let data = {error: true, errorMessage: "Book not found"};
- });
- } else{
- res.sendStatus(401);
- }
- })
- //GET /COMMENTS/:BOOKID
- app.get('/comments/:bookId', (req,res) =>{
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- if (result) {
- Book.findById().populate('comments').populate('users').then(result => {
- res.send(result);
- })
- } else{
- res.sendStatus(401);
- }
- })
- //POST /COMMENTS/:BOOKID//////////////////////////////////////////////////////////////////////////////////
- app.post('/comments/:bookId', (req, res) => {
- //Check if the token is valid or not
- let token = req.headers['authorization'];
- let result = validateToken(token);
- if (result) {
- var payload = jwt.decode(token, {complete: true});
- console.log("point 1");
- let newComment = new Comment({
- book: req.params.bookId,
- user: payload.id, //////I don't know how to get the user ID here
- text: req.body.text,
- score: req.body.score
- });
- newComment.save().then(result => {
- console.log("point 2");
- let data = {error: false, result: result};
- res.send(data);
- }).catch(error => {
- console.log(error);
- let data = {error: true,
- errorMessage:"Error adding comment"};
- res.send(data);
- });
- } else{
- res.sendStatus(401);
- }
- });
- app.listen(8080);
Add Comment
Please, Sign In to add comment