Creating a User resource class from a angular resource is is good in that way that all users becomes a instans of User. That simplify CRUD to each one individual. But it will only works if the response is a array
Here is a simple demonstration (inspired by angular)
// Define User class
var User = $resource('/user/:userId', {userId: '@id'}, {
query: {method: 'GET', isArray: true, params: {limit: 25} }
});
// We can retrieve a collection from the server
var users = User.query(function() {
// GET: /user?limit=25
// server returns: [ {id:456, name:'jimmy'}, {...} ];
var user = users[0];
// each user is an instance of User
expect(user instanceof User).toEqual(true);
user.relation = "Single";
// non GET methods are mapped onto the instances
user.$save();
});
Now that you have 1000 of users, what is the best practice to handle pagination?
I have seen many API in my days and this would be an example of them all bulk together. (that even includes a response status 200 OK with another status code and a error message)
{
errors: null,
status: 200
data: {
href: "/user?limit=30&offset=100&online=true",
offset: 100,
limit: 25,
totalItems: 987,
totalPages: 45, // Math.celi(totalItems / limit)
currentPage: 4,
first: { href: "/user?limit=25&online=true" },
previous: { href: "/user?limit=25&offset=75&online=true" },
next: { href: "/user?limit=25&offset=125&online=true" },
last: { href: "/user?limit=25&offset=975&online=true" },
items: [
{id: 456, name: "jimmy"}
]
}
}
If this would be a public api, would you want all/some of this information to be shipped in the json response? i personally consider this plotted and unnecessary server work that may or may not be used by all users
- a error message should respond with a status code >= 400
- status code is already available on the headers, why have another one?
- the ngResource would just simply work if you would get a array instead of an object without making any response transformation
- every other information is know if you just knew the total amount of users
- this requires the json to return a object to send that information, but you could also use headers and keep the response as an array
I maybe would want some kind of 206 partial content response using just range request headers, i have only used it for file bytes. but could it also be possible to use any other kind of collection?
Range: user=75-100,600- ;get user 75 to 100 and 600 to 978
isn't that what 206 is all about?