How do I create a rest API that I'll use in the React-admin package and then incorporate it as a data provider in the package....I already have a rest API that I created by since it's not fetching I'm assuming I'm doing something wrong that's why it is not fetching. I tried reading the documentation but I can't get anything out of it.
Here's the code for rest Api
const router = require("express").Router();
const Posts = require("../models/post");
//create posts
router.post("/", async (req, res) => {
const newpost = new Posts(req.body);
try {
const savedPost = await newpost.save();
res.status(200).json(savedPost);
} catch {
res.status(500).json("the post didn't go through")
}
})
//delete posts
router.delete("/:id", async (req, res) => {
try {
const deletedPost = await Posts.findByIdAndDelete(req.params.id, {
new: true
});
res.status(200).json(deletedPost);
} catch (err) {
res.status(500).json(err);
}
})
//update posts
router.put("/:id", async (req, res) => {
try {
const updatedPost = await Posts.findByIdAndUpdate(req.params.id, {
$set: req.body
}, {
new: true
});
res.status(200).json(updatedPost);
} catch (err) {
res.status(500).json(err);
}
})
//to get a post
router.get("/:id", async (req, res) => {
try {
const blogPosts = await Posts.findById(req.params.id);
res.status(200).json(blogPosts);
} catch(err) {
res.status(500).json(error);
}
})
//to get all the post
router.get('/', async(req,res)=> {
try{
const allBlogPost = await Posts.find();
res.status(200).json(allBlogPost);
// const total = await allBlogPost.count();
// res.set("x-total-count", total);
// res.send(data);
// res.header('Access-Control-Expose-Headers', 'X-Total-Count')
}catch(err){
res.status(500).json(err);
}
})
module.exports = router;
Here's the code in my app.js
<div className="App">
<BrowserRouter>
<Switch>
<Route path="/home"><HomePage/></Route>
<Route path="/admin">
<Admin dataProvider={simpleRestProvider('http://localhost:5000/', fetchUtils.fetchJson, 'X-Total-Count')} >
<Resource name= "post" list={PostList}/>
</Admin>
</Route>
</Switch>
</BrowserRouter>
In this page documentation from react-admin there is a section Developers from the react-admin community have open-sourced Data Providers for many more backends with a list of existing data provider for many backends.
findByIdAndUpdate seems to be a Mongoose function, is Mongoose your ODM ?