Creating a flat single relationship in Loopback 3 - mongodb

Loopback has a way to make a light relationship using referencesMany where you can say something like:
{
"name": "SomeModel",
"plural": "SomeModel",
// ...,
"relations": {
"images": {
"type": "referencesMany",
"model": "Images",
"options": {
"validate": true
}
}
}
}
Which will allow you to store an array of ObjectId in MongoDB.
I can then do something like:
SomeModel.find({ include: 'images' }) or GET to /api/SomeModel/?filter[include]=images to include a response with nested image objects that are related to the SomeModel.
Is there a good way to do this in a singular case (not an array of values)? Relate one parent to a child? HasOne puts a someModelId on the child and I don't really want to pollute the Image model with BelongsTo as its polymorphic and belongs to all sorts of stuff.

Related

Compound queries

I have a RESTful service that accepts a custom query, like this:
/entities/User?actions=
{
"$link": {
"entityType": "Manager",
"entity": {
"name": "John Smith"
},
"linkName": "managers",
"backLinkName": "account",
"$set": {
"propertyName": "aclWrite",
"propertyValue": {
"$ref": {
"propertyName": "entityId"
}
}
}
}
}
Which simply means:
Create a new Entity of type User
Create a new Entity of type Manager with the field name, linking the User to be created to this Manager through link name "managers"
Then back-linking the Manager entity to be created to the User with a link name "account" and setting the Manager entity write ACL (Access Control List) to the ID of the User to be created.
I created this query structure because I can't find any suitable Query language that can seem to support such action/procedure.
The question here is are there any Query language that can support such compound action/procedure or can GraphQL handle such?
As a specification, GraphQL doesn't care what fields your schema defines, what arguments those fields take or what your field resolvers do with those arguments. So it's perfectly feasible to design a schema that would let the client compose an equivalent mutation:
mutation {
link(
entityType: "Manager"
entity: {
name: "John Smith"
}
linkName: "managers"
backLinkName: "account"
set: {
propertyName: "aclWrite"
propertyValue: {
ref: {
propertyName: "entityId"
}
}
}
) {
# some fields here to return in the response
}
}
GraphQL does not support references to other nodes inside the same query, so you would still probably want a single mutation whose input mirrored your existing API. That said, using GraphQL for this may still be preferable because of request validation, which is all the more important with complex requests like this. Having an IDE like GraphiQL or GraphQL Playground that lets you write your queries using autocomplete is a big plus too.

Removing _embedded from a collection of REST resources

Maybe this goes against REST/HAL principles but I thought that if I was viewing a list of items they should not be contained in an _embedded tag. Below is the details returned when I navigate to /characters in my spring boot application.
I had expected _embedded to not be present for the characterDescriptions since they are the main focus of the page, is it possible to achieve this? Should I try to achieve this or would _embedded be the norm here?
On a related note when I navigate to a particular resource using the link ( like characters/1 for instance) should I be linking back to the /characters parent page or is it acceptable to only contain a self-link at these kinds of endpoints (I will be eventually linking to the user here but this is a general question about REST endpoints )
The controller method that returns this JSON is below the JSON
{
"_embedded": {
"characterDescriptions": [
{
"characterName": "Adrak",
"playerName": "Liam",
"userName": "liam",
"_links": {
"self": {
"href": "http://localhost:8080/characters/1"
}
}
},
{
"characterName": "Thorny",
"playerName": "Aedo",
"userName": "aedo",
"_links": {
"self": {
"href": "http://localhost:8080/characters/2"
}
}
},
{
"characterName": "Anin",
"playerName": "Saoirse",
"userName": "saoirse",
"_links": {
"self": {
"href": "http://localhost:8080/characters/3"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/characters"
}
}
}
Here's the relevant method
#GetMapping
public ResponseEntity<Resources<Resource<CharacterDescription>>> getAllCharacterDescriptions( ) {
List <Resource<CharacterDescription>> characters = repository.findAll()
.stream().map( character -> {
Link characterLink = linkTo(methodOn(CharacterDescriptionController.class)
.getCharacterDescription(character.getCharacterId()))
.withSelfRel();
return new Resource<>(character, characterLink);
}).collect(Collectors.toList());
Link allCharacterLink = linkTo(methodOn(CharacterDescriptionController.class)
.getAllCharacterDescriptions(auth))
.withSelfRel();
Resources<Resource<CharacterDescription>> resources = new Resources<>(characters, allCharacterLink);
return ResponseEntity.ok(resources);
}
According to the HAL spec you can either render a single resource, with its content and set of links, or you can render an aggregate resource, which has room for multiple resources-within-this-resource.
In your domain model, you clearly show multiple documents, each with a distinct self URI (/characters/1, /characters/2, etc.), hence, you aren't serving up a single item resource, but instead an aggregate root.
If you read the HAL spec, you'll find this definition underneath _embedded:
It is an object whose property names are link relation types (as defined by RFC5988) and values are either a Resource Object or an array of Resource Objects.
In fact, looking for the word array in the HAL spec, only leads you to section quoted above, and the _links section.
Hence, _embedded is the proper place to render an array of resources in HAL.

Return an array with a single element using Gson and HAL (Hypertext Application Language)

I'm having problems using Halarious (Java library for the HAL specification) and Gson to serialise a list of links in the _links section with just a single element. The array is serialized into an object instead of being an array with a single link.
EXAMPLE:
What I'm getting now is:
{
"year": 2008,
"_embedded": {
"items": {
"_links": {
"self": {
"href": "/first_item"
}
}
}
}
}
Instead of:
{
"year": 2008,
"_embedded": {
"items": {
"_links": {
"self": [
{
"href": "/first_item"
}
]
}
}
}
}
I solved the same problem with the _embedded section but I can't solve it for the links section.
Thanks
I solved using a workaround. I dont' use #HalLink but a surrogate ad hoc class that contains all the hierarchy and which instance is named "_links".
So using a list of custom Href objects when it has a single link I'll receive back the expected self attribute as list with a single element.
After all the HAL documentation (http://stateless.co/hal_specification.html) says: ​"If you're unsure whether the link should be singular, assume it will be multiple" and from http://blog.stateless.co/post/13296666138/json-linking-with-hal "Where a relation may potentially have multiple links sharing the same key the value should be an array of link objects".
​In this way I won't break consumers having them to deal with either a JSON array or an object.

Apigility: How to render embedded objects?

How do I render embedded objects in Apigility? For example, if I have a 'user' object and it composes a 'country' object, should I be rendering the 'country' object as an embedded object? And how should I do this?
I am using the Zend\Stdlib\Hydrator\ArraySerializable. My getArrayCopy() method simply returns an array of properties that I want exposed. The array keys are the property names. The array values are the property values. In the case of user->country, the value is an object, not a scalar.
When I return the user object from UserResource->fetch(), here's how it is rendered:
{
"id": "1",
"firstName": "Joe",
"lastName": "Bloggs",
"status": "Active",
"email": "test#example.com",
"country": {
"code": "AU",
"name": "Australia"
},
"settings": "0",
"_links": {
"self": {
"href": "http://api.mydomain.local/users/1"
}
}
}
Note that 'country' is not in an _embedded field. If it is supposed to be in _embedded, I would have thought that Apigility would automatically do that (since it automatically adds the _links object).
As a related issue, how do I go about returning other rel links, such as back, forward, etc?
The easiest way to get Apigility to render embedded resources is when there is an API/resource associated to the embedded object. What I mean for your example is that you'd have an API resource that has a country entity. In that case, if your getArrayCopy returned the the CountryEntity, Apigility would render it automatically as an embedded resource.
If your getArrayCopy is returning country as an array with code and name, you'll end up with what you saw.
For the other part, the rel links for first, last, prev and next will come from the fetchAll method when you return a Paginator. Your collection extends from this already, but it needs an adapter. The code could look something like this:
public function fetchAll($params)
{
// Return a \Zend\Db\Select object that will retrieve the
// stuff you want from the database
$select = $this->service->fetchAll($params);
$entityClass = $this->getEntityClass();
$entity = new $entityClass();
$hydrator = new \Zend\Stdlib\ArraySerializable();
$prototype = new \Zend\Db\ResultSet\HydratingResultSet($hydrator, $entity);
$paginator = new \Zend\Paginator\Adapter\DbSelect($select, $this->sql, $prototype);
$collectionClass = $this->getCollectionClass();
return new $collectionClass($paginator);
}
There are other paginator adapters as well - an ArrayAdapter which will take in an array of however big and then paginate it so you only get the desired number of results. The downside to this if you use it with database results, you'll potentially be retrieving and discarding a lot of results. The DbSelect paginator will modify the $select object to add the limit and order clause automatically so you only retrieve the bits you need. There are also adapters if you're using DbTableGateway, Iterators or even callbacks. You can also implement your own of course.
Hope this helps. If you have more specific needs or clarification, please comment and I'll do my best.
I posted this example on github.
https://github.com/martins-smb/apigility-renderCollection-example
Hope this helps.

RESTful master/detail

Having 3 dropdown pickers in a web application. The web application uses a Restful service to populate pickers data.
The two first pickers get their values from something like /years and /colors. The third one should get its values depending on the settings of the two.
So it could be something like /models?year=1&color=red.
The question is, how to make this HATEOAS-compliant (so that the dev does not have to know the way he should create an url to get the models).
The root / gets me a number of links, such as:
{
"_links": {
"colors": "/colors",
"years": "/years",
"models": "???" }
}
What should be instead of ???? If there was some kind of template /models?color={color}&year={year}, the dev would have to create the url. Is this OK?
Or there could be a link to list of years on each color got from /colors and then a link to list of models on each year got from /years?color=red, but i'd have to first choose color, then populate years and then populate models. Any idea if i want to have the model dependent on both color and year, not just the year populated from color?
Is it even possible in this situation to make it hateoas-compliant?
I have not heard of HATEOAS before, but based on what I just read about it, it seems that it supposed to return links to where the consumer of the service can go forward in the "state machine".
In your case that would translate to the links being "function calls". The first two (/colors and /years) are functions that take no parameters (and return "something" at this point), while the third is a function call that takes two parameters: one that is a representation of a color, the other a year. For the first two having a simple URL will suffice for the link, but for the third, you need to include the parameter name/type information as well. Something like:
{
"_links": {
"colors": "/colors",
"years": "/years",
"models": {
"url": "/models",
"param1": {"color"}
"param2": {"year"}
}
}
}
Note: you can use the same layout as "models" for "colors" and "years" as well.
At this point the client knows what the URL to access the functions are and what the parameter (if any) names are to be passed to the function.
One more thing is missing: types. Although you could just use "string", it will not be obvious that the "color" parameter is actually a value from what "/colors" returns. You can be introducing a "type" Color that describes a color (and any functions that operate on a color: give a displayable name, HTML color code, etc.)
The "beefed up" signature becomes:
{
"_links": {
"colors": {
"url": "/colors",
"return": "/type/List?type=/type/Color"
},
"years": {
"url": "/years",
"return": "/type/List?type=/type/Integer"
},
"models": {
"url": "/models",
"param1": {
"name": "color",
"type": "/type/Color"
},
"param2": {
"name": "year",
"type": "/type/Integer"
}
"return": "/type/List?type=/type/Model"
}
}
}
Note: the path "/type" is used just to separate the types from functions, but is not necessary.
This will interchangeably and discoverably describe the functions, what parameters they take, and what values they are returning, so you can use the right value at the right place.
Of course implementing this on the service end will not be easy (especially with parameterized types, like "/type/List" -- think Generics in Java or templates in C++), but this is the most "safe" and "portable" way you can describe your interface to your clients.