SoftInstigate / restheart

Rapid API Development with MongoDB
https://restheart.org
GNU Affero General Public License v3.0
805 stars 171 forks source link

Renaming and adding tags in the API Response (GET) #444

Closed edgars closed 1 year ago

edgars commented 1 year ago

Expected Behavior

When the returned API some of the fields are returned:

*  rh:doc:
* _embedded
*     "_links": {
        "self": {
            "href": "/branches?count=2&hal=f&rep=hal"
        },
        "first": {
            "href": "/branches?pagesize=100&count=2&hal=f&rep=hal"
        },
        "last": {
            "href": "/branches?pagesize=100&count=2&hal=f&rep=hal"
        },

I'd like to change some of those fields, rename them, or even to hide some of them, in gitter, it was mentioned that I could write an interceptor, how could be the best way to do it?

Thanks

ujibang commented 1 year ago

In a response interceptor (see docs at Interceptors) you can modify the response body.

Tip: You can start developing the plugins forking the restheart-plugin-skeleton

Note: I didn't try the code.

@RegisterPlugin(name = "renameLinks",
    interceptPoint = InterceptPoint.RESPONSE,
    description = "removes the property 'secret' from GET /coll")
public class RenameLinks implements MongoInterceptor {

@Override
    public void handle(MongoRequest request, MongoResponse response) throws Exception {
        var content = response.getContent().asDocument();
        var _embedded = content.get("_embedded");
        var _links = _embedded.remove("_links"); // here we remove the _links document

        var self = _links.get("self");

        _embedded.put("renamedSelf", self); // we add back the self link in the _embedded document as renamedSelf
    }

    /**
     * resolve true for GET /coll requests
     */
    @Override
    public boolean resolve(MongoRequest request, MongoResponse response) {
        return request.isGet()
            && response.getContent() != null
            && response.getContent().isDocument()
            && "coll".equalsIgnoreCase(request.getCollectionName());
    }
}
ujibang commented 1 year ago

closing this. Feel free to reopen if you need more help or ask directly in our slack channel, here you have the invite link