I checked this backend code using Postman. It sometimes works properly. But, sometimes, it does not work. What's the matter with this code?

Issue

I checked this backend code using Postman. It sometimes works properly. But, sometimes, it does not work. What’s the matter with this code?

I used the technology koa.js. I create dao file, api file, and router file to handle the backend.

This is the server.js file

server.js

const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const cors = require('@koa/cors'); const dbConfig = require('./dal/index');

const studentRouter = require('./router/student.router'); const userRouter = require('./router/user.router');

const app = new Koa();

app.use(bodyParser()); app.use(cors()); app.use.dbConfig;

app.use(studentRouter.routes()).use(studentRouter.allowedMethods()); app.use(userRouter.routes()).use(userRouter.allowedMethods());

app.listen(5000, ctx=>{ console.log("App Is Running On Port 5000") })

This is the student.dao file.

student.dao

const {ObjectId} = require('mongodb');
const student = require('./index').db("newDb").collection("NewCollection");

const save = async ({name,age,city}) => {
    const result = await student.insertOne({
        name,
        age,
        city,
    })
    return result;
}

const getAll = async()=>{
   const findResult = await student.find({}).toArray();
   return findResult;
}

const getById = async(id)=>{
    const findResult = await student.findOne({_id:ObjectId(id)})
    return findResult;
}



const update = async(id,{name,age,city})=>{
    const updateResult = await student.replaceOne({_id:id},{name,age,city})    //ObjectId(id)
    return updateResult;
}


const remove = async(id)=>{
    const deleteResult = student.deleteOne({_id:id});
    return deleteResult;
}


module.exports = {remove,update,getAll,getById,save}

This studentapi.js file.

studentapi.js

const {remove,getAll,getById,update,save} =require('../dal/student.dao');


const addStudent = async({name,age,city})=>{
    const student ={
        name,
        age,
        city,
    }
    return await save(student);
}

const getStudents = async()=>{
    return await getAll();
}

const getStudent = async(id)=>{
    return await getById(id);
}


const updateStudent = async (id,{name,age,city})=>{
    const student = {
        name,
        age,
        city,
    }
    return await update(id,student);


}




const deleteStudent = async(id)=>{
    return await remove(id);
}


module.exports = {deleteStudent,updateStudent,getStudent,getStudents,addStudent}

studentRouter.js

const Router = require('@koa/router');

const {addStudent,updateStudent,getStudent,getStudents,deleteStudent} = require('../api/student.api');

const studentRouter = new Router({
    prefix : '/student'
})



studentRouter.post("/",async ctx =>{
    const data = ctx.request.body;
    const post = addStudent(data);
    ctx.set('Content-Type','application/json');
    ctx.body = {success:true}
    ctx.status = 201;
})


studentRouter.get("/",async ctx=>{
    const student = getStudents();
    ctx.body ={success:true, existingData:student}
    ctx.set('Content-Type','application/json')
    ctx.status = 200;

})


studentRouter.get("/:id",async ctx=>{
    const id = ctx.params.id;
    const student = getStudent(id);
    ctx.body = {success:true, existingData:student}
    ctx.set('Context-Type','application/json'); 
    ctx.status = 200; 
})



studentRouter.put("/:id", async ctx=>{
    var ObjectID = require('mongodb').ObjectId;
    var id = new ObjectID(ctx.params.id);
    let student = ctx.request.body;
    student =  updateStudent(id,student);
    ctx.set('Context-Type','application/json' );
    ctx.body = {success:true, existingData:student}
    ctx.status = 200;
})



studentRouter.delete("/:id", async ctx=>{
    var ObjectID = require ('mongodb').ObjectId;
    var id = new ObjectID(ctx.params.id);
  
    const student = deleteStudent(id);
    ctx.body = {success:true}
    ctx.status = 204; 
})


module.exports = studentRouter;

Solution

In the router file, please use the await ‘ keyword before these functions

addStudent()
getStudents()
getStudent()
updateStudent()
deleteStudent()

As an example

studentRouter.post("/",async ctx =>{
    const data = ctx.request.body;
    const post = await addStudent(data);
    ctx.set('Content-Type','application/json');
    ctx.body = {success:true}
    ctx.status = 201;
})

Answered By – abishankar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published