const express = require('express');
const bodyParser = require('body-parser');
const Sequelize = require('sequelize');
const { STRING, INTEGER } = require('sequelize');
const sequelize = new Sequelize({
dialect: 'sqlite',
storate: 'homework.db'
});
const Student = sequelize.define('student', {
name: Sequelize.STRING,
address: Sequelize.STRING,
age: Sequelize.INTEGER
}, {
timestamps: false
});
const app = express();
app.use(bodyParser.json());
app.get('/create', async (req, res) => {
try {
await sequelize.sync({ force: true });
for (let i = 0; i < 10; i++) {
const student = new Student({
name: 'name ' + i,
address: 'some address on ' + i + 'th street',
age: 30 + i
});
await student.save();
}
res.status(201).json({ message: 'created' });
} catch (err) {
console.warn(err.stack)
res.status(500).json({ message: 'server error' });
}
});
app.get('/students', async (req, res) => {
try {
const students = await Student.findAll();
res.status(200).json(students);
} catch (err) {
console.warn(err.stack);
res.status(500).json({ message: 'server error' });
}
});
app.post('/students', async (req, res) => {
try {
//TODO
if (req.body !== null) {
const student = await Student.create(req.body);
if (!(typeof(student.name) === STRING && typeof(student.address) === STRING && typeof(student.age) === INTEGER)) {
if (student.age > 0) {
return res.status(201).json({ message: "created" });
} else {
res.status(400).json({ message: "age should be a positive number" });
}
} else {
res.status(400).json({ message: "malformed request" });
}
} else {
res.status(400).json({ message: "body is missing" });
}
} catch (err) {
console.warn(err.stack);
res.status(500).json({ message: 'server error' });
}
});
module.exports = app;
Right sooo I have a little school project here with apparently some simple http verbs implemented in node js. The problem is that I have some tests defined(all of them related to the last POST method) and out of five, only two of them pass and idk why. Can anyone tell how should I modify that post in order for the tests to be satisfied? The first code is the app js file and the second one is the server side.
The tests are as follws:
-
if request body is not sent server should respond with status code 400 and {“message”:”body is missing} -> failed
-
if request body is present but did not follow the specified format, server should respond with status code 400 and {“message”:”malformed request”} -> failed
-
age should not be negative -> passed
-
a student can be added -> passed
-
the student list is valid -> failed
const app = require('./app') app.listen(8080, () => { console.log('Server started on port 8080...') })