How to push data into db.json file when customizing server.post() - javascript

my code:
const jsonServer = require('json-server');
const { v4 } = require('uuid');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const db = router.db;
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.post('/api/register', (req, res, next) => {
const userRegister = req.body;
const usersDb = db.get('users').value();
usersDb.push(
JSON.stringify({
...userRegister,
address: '',
birthDay: null,
isCustomer: true,
isActive: true,
avatar: '',
createAt: Date.now(),
updateAt: Date.now(),
id: v4(),
}),
);
});
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now();
req.body.updateAt = Date.now();
}
next();
});
router.render = (req, res) => {
res.jsonp({
body: res.locals.data,
});
};
server.use('/api', router);
server.listen(3002, () => {
console.log('JSON Server is running');
});
I need to customize the path and I'm having trouble that I can't add data to the db.json file.
You can see usersDb.push is not working. I want to know how can I add new data to db.json file using custom server.post()

Related

Status Code 502 - Server Error - Node.js Express & MongoDB - Incomplete response received from application

I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};

How can you put a default image in multer if no image is uploaded?

I'm trying to set up multer but I'm having some issues with the image, as for now, when I don't upload any image, the server gives me an error which doesn't allow me to continue. I want that even if the image is not uploaded, to still store the values in the database.
This is where I have my multer configured:
const express = require('express');
const router = express.Router();
const multer = require('multer');
const Clients = require('../models/clients.js')
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "../emaildragger/public/uploads")
},
filename: (req, file, callback) => {
callback(null, file.originalname)
}
})
const upload = multer({storage: storage})
router.route('/').get((req, res) => {
Clients.find()
.then(client => res.json(client))
.catch(err => res.status(400).json('Error:' + err))
})
router.route('/:id').get((req, res) => {
Clients.findById(req.params.id)
.then(client => res.json(client))
.catch(err => res.status(400).json("Error" + err))
})
router.route('/add').post(upload.single("image"), (req, res) => {
const newClient = new Clients({
image: req.file.originalname,
firstName: req.body.firstName,
lastName: req.body.lastName,
weight: req.body.weight,
BMI: req.body.BMI
})
newClient.save()
.then (() => res.json(newClient))
.catch(err => res.status(400).json('error' + err))
})
module.exports = router
Here is my models:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var clientsSchema = new Schema(
{
image:
{ type: String, required: false, default: 'Screenshot_293.png'},
firstName: { type: String, required: true },
lastName: { type: String, required: true },
weight: { type: String, required: false },
BMI: { type: String, required: false }
}
);
const Clients = mongoose.model("clients", clientsSchema)
module.exports = Clients
The error is in your server because you added Multer as an middleware, and later in your controller you are trying to access the originalname of the uploaded file. If you didn't send the image, then Multer will not parse and upload it, and the file will not exist. In that case you will try to access to the originalname property of something that does not exist, so your server will throw an error.
Try to change you code like this:
router.route('/add').post(upload.single("image"), (req, res) => {
let client = {
firstName: req.body.firstName,
lastName: req.body.lastName,
weight: req.body.weight,
BMI: req.body.BMI
}
if(req.file && req.file.originalname) client.image = req.file.originalname;
const newClient = new Clients(client)
newClient.save()
.then (() => res.json(newClient))
.catch(err => res.status(400).json('error' + err))
})

Upload multiple files from dynamically created form inputs

I'm learning MEAN stack and have trubles on a files upload. I have a company form:
this.companyForm = this.fb.group({
trucks: this.fb.array([]),
...
});
Trucks field is dynamicly created:
newTruck(): FormGroup {
this.added = false;
return this.fb.group({
...
TLic: new FormControl(null, {
validators: [Validators.required]
}),
Lic: new FormControl(null, {
validators: [Validators.required]
}),
CMRLic: new FormControl(null, {
validators: [Validators.required]
})
})
}
addTruck() {
this.trucks().push(this.newTruck());
}
On save form:
this.authService.createUserStep1(
...
this.companyForm.value.trucks
);
AuthService:
createUserStep1(... trucks: Array<any>) {
const AuthDataStep1: AuthDataStep1 = {
...
trucks: trucks
};
this.http.put(BACKEND_URL + "signupStep1/", AuthDataStep1).subscribe(
() => {
this.authStatusListener.next(true);
this.router.navigate(["auth/signupStep2"]);
},
error => {
this.authStatusListener.next(false);
}
);
}
Nodejs controller where I write to DB:
exports.createUserStep1 = (req, res, next) => {
...
for (i = 0; i < req.body.trucks.length; i++) {
const truck = new Truck({
...
TLic: req.body.trucks[i].file.TLic[0].filename,
Lic: req.body.trucks[i].file.Lic[0].filename,
CMRLic: req.body.trucks[i].file.CMRLic[0].filename,
});
Truck.create(truck);
}
})
}
Middleware for files upload:
const multer = require("multer");
var path = require('path');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "backend/truckdocs");
},
filename: (req, file, cb) => {
const name = file.originalname
.toLowerCase()
.split(" ")
.join("-");
cb(null, name + "-" + Date.now() + "." + path.extname(file.originalname));
}
});
module.exports = multer({ storage: storage }).fields([
{
name: "TLic", maxCount: 1
}, {
name: "Lic", maxCount: 1,
}, {
name: "CMRLic", maxCount: 1
}
]);
and route
const express = require("express");
const UserController = require("../controllers/user");
const extractTruckFiles = require("../middleware/truckfiles");
const checkAuth = require("../middleware/check-auth");
const router = express.Router();
/*App*/
...
router.put("/signupStep1", checkAuth, extractTruckFiles, UserController.createUserStep1);
I want to create x number of trucks in form and for each truck upload 3 files(TLic, Lic, CMRLic).What is the best way to achieve this? I know it needs time for you to get into my code and I'm very thankful in advance.
This is how i did for a ecommerce where i upload 3 photo. I have done it with MVC pattern and i called multer in route file.
const express = require("express")
const multer = require("multer");
const router = express.Router()
const productController = require("../../controller/vendor/product")
const app = express();
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-') + '-' +file.originalname)
}
});
const fileFilter = (req, file, cb) => {
if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
cb(null, true)
} else {
cb(null, false)
}
}
let filehandler = app.use(multer({storage : fileStorage, fileFilter: fileFilter }).array('image',3))
/* #GET product Page request */
router.get('/products', productController.getProduct)
/* #GET add product page Request */
router.get('/add-product', productController.getAddProduct)
/* #POST Request */
router.post('/add-product', filehandler, productController.postAddProduct)
/* #GET AJAX Request findind subcategory */
router.get("/getSubCategory/:id", productController.getSubCategory);
module.exports = router

"error": "select * from `alliance` where `alliance_description` = {} - SQLITE_ERROR: no such table: alliance

The problem => "error": "select * from alliance where alliance_description = {} - SQLITE_ERROR: no such table: alliance"
$ npm run start:dev
> rest-api#1.0.0 start:dev D:\OSSE\back-end
> nodemon src/server.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node src/server.js`
migrations [ 2, [] ]
Listening on Port 5000!
sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs
http://knexjs.org/#Builder-insert).
GET /alliance 500 149.999 ms - 110
sqlite does not support inserting default values. Set the useNullAsDefault flag to hide this warning. (see docs
http://knexjs.org/#Builder-insert).
GET /alliance 500 6.629 ms - 110
GET /favicon.ico 404 0.703 ms - 40
Knex.js Config
const path = require('path')
require('dotenv').config()
const {
DATABASE_URL = 'postgresql://postgres#localhost/postgres',
} = process.env
module.exports = {
development: {
client: 'postgresql',
connection: DATABASE_URL,
pool: { min: 0, max: 100 },
migrations: {
directory: path.join(__dirname, 'src', 'db', 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'src', 'db', 'seeds'),
},
useNullAsDefault: true,
},
production: {
client: 'postgresql',
connection: DATABASE_URL,
pool: { min: 0, max: 100 },
migrations: {
directory: path.join(__dirname, 'src', 'db', 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'src', 'db', 'seeds'),
},
useNullAsDefault: true,
},
test: {
client: 'sqlite3',
connection: {
filename: ':memory:',
},
migrations: {
directory: path.join(__dirname, 'src', 'db', 'migrations'),
},
seeds: {
directory: path.join(__dirname, 'src', 'db', 'seeds'),
},
useNullAsDefault: true,
},
}
Knex Connection
const env = process.env.NODE_ENV || 'development'
const config = require('../../knexfile')[env]
const knex = require('knex')(config)
module.exports = knex
Alliance.controller
const service = require('./alliance.service')
const wrapper = require('../errors/asyncErrorBoundary')
const list = async (req, res, next) => {
const { alliance_description } = req.query
const data = await service.list(req.query)
if (alliance_description) {
const data = await service.list(alliance_description)
res.json({
data: alliance_description,
})
return
}
return res.json({ data })
}
function allianceExists(req, res, next) {
const allianceId = req.params.alliance_id
const foundAlliance = alliance.find(
(alliances) => alliances.id === alliance_id
)
if (foundAlliance) {
res.locals.dish = foundAlliance
return next()
}
next({
status: 404,
message: `Alliance ID ${allianceId} Doesn't Exist`,
})
}
function checkAllianceId(req, res, next) {
const allianceId = req.params.alliance_id
const id = req.body.data.id
if (allianceId !== id && id !== undefined && (id !== '') & (id !== null)) {
return next({
status: 400,
message: `Alliance ID does not match route id. Alliance: ${id}, Route: ${allianceId}`,
})
}
return next()
}
const update = async (req, res, next) => {
const { alliance_id } = req.params
const data = await service.update(alliance_id, req.body.data)
res.status(200).json({
data: data[0],
})
}
const create = async (req, res, next) => {
const newAlliance = res.locals.validAlliance
const newRes = await service.create(newAlliance)
res.status(201).json({ data: newRes[0] })
}
const show = async (req, res, next) => {
const data = await service.show()
return res.json({ data })
}
const read = async (req, res, next) => {
const alliances = res.locals.alliance
res.status(200).json({ data: alliance[0] })
}
const isValid = (req, res, next) => {
if (!req.body.data)
return next({ status: 400, message: 'No alliance selected' })
const { alliance_name, alliance_description } = req.body.data
const requiredFields = ['alliance_name', 'alliance_description']
for (const field of requiredFields) {
if (!req.body.data[field]) {
return next({ status: 400, message: `Invalid input for ${field}` })
}
}
res.locals.validAlliance = req.body.data
next()
}
const destroy = async (req, res) => {
const { alliance_id } = rq.params
const des = await service.destroy(alliance_id)
res.status(200)
}
module.exports = {
list: [wrapper(list)],
show: [wrapper(show)],
read: [wrapper(checkAllianceId), wrapper(allianceExists), wrapper(read)],
create: [wrapper(isValid), wrapper(create)],
update: [wrapper(isValid), wrapper(allianceExists), wrapper(update)],
destroy: [wrapper(destroy)],
}
Alliance.Router
const router = require('express').Router()
const controller = require('./alliance.controller')
const methodNotAllowed = require('../errors/methodNotAllowed')
router.route('/').get(controller.list).all(methodNotAllowed)
router
.route('/:allianceId')
.get(controller.list)
.post(controller.create)
.put(controller.update)
.all(methodNotAllowed)
router
.route('/:allianceId/:userId')
.get(controller.list)
.put(controller.update)
.delete(controller.destroy)
.all(methodNotAllowed)
module.exports = router
Alliance.service
const { default: knex } = require('knex')
const listAlliancesById = (knex, allianceId) =>
knex('alliances as a').where({ 'a.alliance_id': allianceId })
const list = (alliance_description) => {
return knex('alliance')
.select('*')
.from('alliance')
.where({ alliance_description: alliance_description })
// .orderBy('alliance_id')
}
const show = () => {
return knex('alliance').select('*')
}
const read = (alliance_id) => {
return knex('alliance').select('*').where({ alliance_id: alliance_id })
}
const create = (alliance) => {
return knex('alliance').insert(alliance, '*')
}
const update = (alliance_id, updatedAlliance) => {
return knex('alliance')
.where({ alliance_id: alliance_id })
.update(updatedAlliance)
.returning('*')
}
const destroy = (alliance) => {
return knex('alliance').delete(alliance).returning('*')
}
module.exports = {
list,
show,
read,
create,
listAlliancesById,
update,
destroy,
}
Database query
I hope someone can help me figure out this issue.
you are getting error from sqlite dbms:
SQLITE_ERROR: no such table: alliance"
definitely your app is connected to sqlite and not postgresql server and it can't find that table in there.
so look into your config/connection strings to find out where your knex app is reading the database connection from
I solved it:
const { default: knex } = require('knex')
const knex = require(../db/connection) // <==== ANSWER
// was missing out of the .service file

FCC Exercise Tracker adding exercises

I am stuck on Test #3 and at a loss. Any help, advice or suggestions are welcome. I am using Glitch to write my code. Everything syncs up to my database which is MongoDB. Just can't pass that test and I would suspect you would need to in order to get 4, 5, and 6 done. I am new to coding, so be nice lol Thank you
https://github.com/rbill314/Exercise-Tracker-.git
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const moment = require("moment");
const shortId = require("shortid");
/*Connect to database*/
mongoose.connect(process.env.URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
if (mongoose.connection.readyState) {
console.log("Holy Crap! It Connected");
} else if (!mongoose.connection.readyState) {
console.log("WHACHA DO!!!");
}
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
/*Model*/
const userSchema = new mongoose.Schema({
_id: { type: String, required: true, default: shortId.generate },
username: { type: String, required: true },
count: { type: Number, default: 0 },
log: [
{
description: { type: String },
duration: { type: Number },
date: { type: Date }
}
]
});
const User = mongoose.model("User", userSchema);
/*Test 1: You can POST to /api/users with form data username to create a new user.
The returned response will be an object with username and _id properties.*/
app.post("/api/users", (req, res) => {
User.findOne({ username: req.body.username }, (err, foundUser) => {
if (err) return;
if (foundUser) {
res.send("Username Taken");
} else {
const newUser = new User({
username: req.body.username
});
newUser.save();
res.json({
username: req.body.username,
_id: newUser._id
});
}
});
});
/*Test 2: You can make a GET request to /api/users to get an array of all users.
Each element in the array is an object containing a user's username and _id.*/
app.get("/api/users", (req, res) => {
User.find({}, (err, users) => {
if (err) return;
res.json(users);
});
});
/*Test 3: You can POST to /api/users/:_id/exercises with form data description, duration, and optionally date.
If no date is supplied, the current date will be used.
The response returned will be the user object with the exercise fields added.*/
app.post("/api/users/:_id/exercises", (req, res) => {
const { _id, description, duration, date } = req.body || req.params;
User.findOne({ _id }, (err, userFound) => {
if (err)
return res.json({
error: "Counld not find Carmen Sandiego"
});
let exerDate = new Date();
if (req.body.date && req.body.date !== "") {
exerDate = new Date(req.body.date);
}
const exercise = {
description: description,
duration: duration,
date: exerDate
};
userFound.log.push(exercise);
userFound.count = userFound.log.length;
userFound.save((err, data) => {
if (err)
return res.json({
error: "Not letting you save today"
});
const lenOfLog = data.log.length;
let displayDate = moment(exercise.date)
.toDate()
.toDateString();
let sendData = {
username: data.username,
description: data.log[lenOfLog - 1].description,
duration: data.log[lenOfLog - 1].duration,
_id: data._id,
date: displayDate
};
res.send(sendData);
});
});
});
/*Test 4: You can make a GET request to /api/users/:_id/logs to retrieve a full exercise log of any user.
The returned response will be the user object with a log array of all the exercises added.
Each log item has the description, duration, and date properties.*/
/*Test 5: A request to a user's log (/api/users/:_id/logs) returns an object with a count
property representing the number of exercises returned.*/
/*Test 6: You can add from, to and limit parameters to a /api/users/:_id/logs request to retrieve part
of the log of any user. from and to are dates in yyyy-mm-dd format. limit is an integer of how many
logs to send back.*/
/*listener*/
const listener = app.listen(process.env.PORT || 3000, () => {
console.log("Shhhhh!!!! Spying on port " + listener.address().port);
});
//Excercise Schema
const exSchema=new Schema({
description:{
type:String,
required:true
},
duration:{
type:Number,
required:true
},
date:String
})
//User Schema
const userSchema=new Schema({
username:{
type:String,
required:true
},
log:[exSchema]
})
const User=mongoose.model("User",userSchema)
const ExModel=mongoose.model("Excercise",exSchema)
app.use(cors())
app.use(express.static('public'))
app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
//Endpoind Of user
app.route("/api/users").post(async(req,res)=>{
const{username}=req.body
const user=await User.create({username:username})
res.json(user)
}).get(async(req,res)=>{
const user=await User.find()
res.json(user)
})
//Excercise Endpoint
app.post("/api/users/:_id/exercises",async(req,res)=>{
const{description,duration,date}=req.body
const{_id}=req.params
let excercise=await ExModel.create({description,duration:parseInt(duration),date})
if(excercise.date===""){
excercise.date=new Date(Date.now()).toISOString().substr(0,10)
}
await User.findByIdAndUpdate(_id,{$push:{log:excercise} },{new:true},(err,user)=>{
let responseObj={}
responseObj["_id"]=user._id
responseObj["username"]=user.username
responseObj["date"]=new Date(excercise.date).toDateString(),
responseObj["description"]=excercise.description,
responseObj["duration"]=excercise.duration
res.json(responseObj)
})
res.json({})
})
//Logs Endpoint
app.get("/api/users/:_id/logs",async(req,res)=>{
if(req.params._id){
await User.findById(req.params._id,(err,result)=>{
if(!err){
let responseObj={}
responseObj["_id"]=result._id
responseObj["username"]=result.username
responseObj["count"]=result.log.length
if(req.query.limit){
responseObj["log"]=result.log.slice(0,req.query.limit)
}else{
responseObj["log"]=result.log.map(log=>({
description:log.description,
duration:log.duration,
date:new Date(log.date).toDateString()
}))
}
if(req.query.from||req.query.to){
let fromDate=new Date(0)
let toDate=new Date()
if(req.query.from){
fromDate=new Date(req.query.from)
}
if(req.query.to){
toDate=new Date(req.query.to)
}
fromDate=fromDate.getTime()
toDate=toDate.getTime()
responseObj["log"]=result.log.filter((session)=>{
let sessionDate=new Date(session.date).getTime()
return sessionDate>=fromDate&&sessionDate<=toDate
})
}
res.json(responseObj)
}else{
res.json({err:err})
}
})
}else{
res.json({user:"user not found with this id"})
}
})
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const { Schema } = require('mongoose')
const bodyParser = require('body-parser')
require('dotenv').config()
const MONGO_URL = process.env.MONGO_URL;
mongoose.connect(MONGO_URL);
const userSchema = new Schema ({
username: {
type: String,
required: true
},
log: [{
date: String,
duration: {type: Number,
required: true
},
description: {type: String,
required: true
},
}],
count: Number
});
const User = mongoose.model('User', userSchema); //creates new user
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
app.route('/api/users')
.post((req, res) => {
const username = req.body.username
const user = new User({ username, count: 0 })
user.save((err, data) => {
if (err) {
res.json({error: err})
}
res.json(data)
})
})
.get((req, res) => {
User.find((err, data) => {
if (data) {
res.json(data)
}
})
})
app.post('/api/users/:_id/exercises', (req, res) => {
const { description } = req.body
const duration = parseInt(req.body.duration)
const date = req.body.date ? 'Mon Jan 01 1990' : 'Thu Nov 04 2021'
const id = req.params._id
const exercise = {
date,
duration,
description,
}
User.findByIdAndUpdate(id, {
$push: { log: exercise },
$inc: {count: 1}
}, {new: true}, (err, user) => {
if (user) {
const updatedExercise = {
_id: id,
username: user.username,
...exercise
};
res.json(updatedExercise)
}
})
})
app.get('/api/users/:_id/logs', (req, res) => {
const { from, to, limit } = req.query
console.log(from, to, limit)
User.findById(req.params._id, (err, user) => {
if (user) {
if (from || to || limit) {
const logs = user.log
const filteredLogs = logs
.filter(log => {
const formattedLogDate = (new Date(log.date)).toISOString().split('T')[0]
return true
})
const slicedLogs = limit ? filteredLogs.slice(0, limit) : filteredLogs
user.log = slicedLogs
}
res.json(user)
}
})
})
app.get('/mongo-health', (req, res) => {
res.json({ status: mongoose.connection.readyState
})
})
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})

Categories