jsonangulartypescriptjson-server

How to delete all in json server


I am using this json server in my Angular app, to create, fetch, and delete posts.

In the following method, I delete a post with a specified id:

deleteConsumer(post: Post): Observable<Post> {
    const url = `${this.apiUrl}/${post.id}`;
    return this.httpClient.delete<Post>(url);
}

I looked at the .delete code and searched for something like a .deleteall but could not find it. Is there really no such method that would delete everything?

If there really isn't, then my attempt at doing it myself is not paying off, because what I have done is not working:

deleteConsumers(): Observable<Post> {   
    let i: number = 0;
    this.httpClient.get<Post[]>(this.apiUrl).forEach(
      () => {
        ++i;
        const url = `${this.apiUrl}/${i}`;
        return this.httpClient.delete<Post>(url);
      }
    );
}

Obviously, this is wrong in terms of return type, but I cannot figure out what to do... How can I modify the first method, so it would go through all the json objects in my db.json file; meaning iterate through all the existing posts and delete them all?


Solution

  • I did encounter this when using json-server with Vue.js and I realized that there was no special function to delete all at once. I had to work around it.

    So, for example in your case, I would first map the posts array to get a new array with only the post ids:

    const postsIdsArray = this.posts.map((post) => post.id)
    

    Then, assuming you already have a function to delete one post given the id, I would then execute the function for each of the ids in the array:

    postsIdsArray.forEach((id) => this.deletePost(id))
    

    Just combine the two lines in one JavaScript function (in this case I used Vue.js):

    deleteAllPosts(){
       const postsIdsArray = this.posts.map((post) => post.id)
       postsIdsArray.forEach((id) => this.deletePost(id))
    }