im trying to make function do delete a specific user by his id but the thing happpening is that it deletes all the users in the list. when i send get request with postman it returns an empty array what am i doing wrong? i don't have a database but i have local json file which i created and i do everything with that json here is user.controller.ts
// const events_db = ["123",112333333];
import user from "./user.json"
console.log(user)
export const getUser = (ctx: { body?: any; status: number; }) => {
ctx.body = user;
ctx.status = 200;
};
export const addUser = (ctx: { request: { body?: any; }; body: string; status: number; }) => {
user.Users.push(ctx.request.body);
ctx.body = "User Created!";
ctx.status = 201;
};
export const deleteUser = ((ctx: { body: string; status: number; }) =>{
const filtered = user.Users.filter((obj,index) => obj.id !== user.Users[index].id)
console.log(filtered)
user.Users = filtered
ctx.body= "user deleted"
ctx.status = 202
})
and here is user-routes.ts
import Router from "koa-router";
const router = new Router();
import {getUser, addUser,deleteUser} from "./controllers/user.controllers"
router.get("/user_list", getUser);
router.post("/add_user", addUser);
router.delete("/:id/delete_user", deleteUser)
// router.put("/:id/update_user" , update_user)
export default router;
and here is the user.json
{
"Users" : [
{
"id":"1",
"username" : "luka",
"email" : "[email protected]",
"phone_number": "5555555",
"password" : "123",
"personal_number" : "1111",
"first_name":"lll",
"last_name": "llll",
"birth_date":"010101",
"nick_name":"abbb",
"gender_id" : "1",
"culture_id":"2",
"role_id":"3",
"department_id":"5",
"group_id": "1",
"avatar" : ""
},
{
"id":"2",
"username" : "lukaa",
"email" : "[email protected]",
"phone_number": "55552555",
"password" : "1233",
"personal_number" : "11111",
"first_name":"l2ll",
"last_name": "lll3l",
"birth_date":"0104101",
"nick_name":"abb5b",
"gender_id" : "61",
"culture_id":"211",
"role_id":"322",
"department_id":"335",
"group_id": "144#",
"avatar" : ""
}
]
}
CodePudding user response:
The problem is the line
const filtered = user.Users.filter((obj,index) => obj.id !== user.Users[index].id)
Here you are comparing the same object with itself and there of course the id is always the same so the not equal !==
will the return NO object. You are not using the params.id from the delete route.
Modify your code to:
const filtered = user.Users.filter((obj) => obj.id !== ctx.params.id)
Code not testet but I think you get the point ...