On Thu, 22 Sep 2016 21:18:35 GMT, Leo wrote:
I'm trying to implement a rest api. It works with a normal request but I'd like to return a jsonp when called with a callback function.
This function returns a json array of all restaurants in the database.
Json getRestaurants() { Json restaurantList = Json.emptyObject(); restaurantList["restaurants"] = Json.emptyArray(); foreach (doc; collection.find()) { restaurantList["restaurants"] ~= [doc.toJson()]; } return restaurantList; }
How could I implement it so that with the url
/restaurants?callback=parse
it returnsparse({"restaurants":[{"_id":"...}]})
?Thank you for taking the time.
If I understand it right, then you can do something like this:
Json getRestaurants(string callback = "")
{
if (callback == "parse") {
return parse({"restaurants": [...]});
}
Json restaurantList = Json.emptyObject();
restaurantList["restaurants"] = Json.emptyArray();
foreach (doc; collection.find())
{
restaurantList["restaurants"] ~= [doc.toJson()];
}
return restaurantList;
}
BTW, a slightly shorter and more efficient alternative to the foreach
loop is restaurantList["restaurants"] = Json(collection.find().map!(d => d.toJson()).array);
(the return value of find()
is a proper input range).