So, I’m trying to show how Restivus API works and Meteor is nice to my colleagues.
I’ve made a simple blog app at http://askar-blog.meteor.com/ (thanks to DiscoverMeteor book).
My repo https://github.com/tenzan/blog
(I’m reading https://github.com/kahmali/meteor-restivus#restivus)
I have three collections:
users
posts
comments
So, post
has many comments
. Usually, we used to have comments
as a nested documents inside of a post
, but from the Meteor’s nature these two attributes are split up into different collections.
I want to implement a REST API, so that I can access (including CRUD
operations) posts
and collections
in the way:
http://example.com/api/posts
- all posts
http://example.com/api/posts/post_id
- a specific post
http://example.com/api/posts/post_id/comments
- all comments
that belongs to a given post
http://example.com/api/posts/post_id/comments/comment_id
- a specific comment
that belongs to a given post
If you have a look at my repo, you will see there’re posts.js
and comments.js
under lib/collections
.
As I understood, to enable REST API, I will need the following snippet in the posts.js
:
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true
});
// Generates: GET, POST on /api/post and GET, PUT, DELETE on
// /api/items/:id for the Posts collection
Api.addCollection(Posts);
// Generates: POST on /api/users and GET, DELETE /api/users/:id for
// Meteor.users collection
Api.addCollection(Meteor.users, {
excludedEndpoints: ['getAll', 'put'],
routeOptions: {
authRequired: true
},
endpoints: {
post: {
authRequired: false
},
delete: {
roleRequired: 'admin'
}
}
});
As you see, I’ve added Api.addCollection(Posts);
and I’ve confirmed I can access all posts
or a specific one.
My questions:
1- How can I setup API to access comments
for their parent post
?
2 - Will I have to have to following code to access posts
? I’m asking because, I’m already able to access them as I have Api.addCollection(Posts);
:
Maps to: /api/posts/:id
Api.addRoute('posts/:id', {authRequired: true}, {
get: function () {
return Posts.findOne(this.urlParams.id);
},
delete: {
roleRequired: ['author', 'admin'],
action: function () {
if (Articles.remove(this.urlParams.id)) {
return {status: 'success', data: {message: 'Post removed'}};
}
return {
statusCode: 404,
body: {status: 'fail', message: 'Post not found'}
};
}
}
});
I apologise, I got confused myself trying to figure out the correct way of making a REST API.
Please feel free to add anything important on this regard I have missed here.