Allow dynamic meta content
See original GitHub issue@SeyZ - first off, thumbs up for a great framework-agnostic, lightweight and easy-to-use library 👍 Just what I’ve been looking for!
The only thing I find lacking at the moment is the ability to add dynamic meta data at the point of serialisation. At the moment, you can only add meta when creating the serialiser instance, and seems a bit unintuitive to recreate the serialiser every time I need to change the meta.
In my case, I’m looking to add some extra information regarding pagination, such as total count. In keeping with the spec, this type of additional information should live in the top-level meta. An example of this can be seen in the extensions section here, under Profiles: link
The easiest way I can think of is to add an optional opts param to the serialise method. You can then specify a meta value in opts, and on the plus side, this also serves as a nice container if you want to allow any other options for the serialise method in the future. We can then merge it with any existing meta from the serialiser instance like so:
module.exports = function (collectionName, records, opts) {
this.serialize = function (records, opts) {
var that = this;
var payload = {};
...
if (that.opts.meta) {
payload.meta = that.opts.meta;
}
if (opts.meta) {
if (payload.meta) {
for (var i in opts.meta) {
payload.meta[i] = opts.meta[i];
}
} else {
payload.meta = opts.meta;
}
}
...
Just gave it a run-through, and seems to work well. If anybody seconds the approach, I’m happy to do a PR.
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (2 by maintainers)
Hey @allistercsmith @bradbumbalough @mrkvon @sazzer
I’ve added the possibility to set a function for the meta key: https://github.com/SeyZ/jsonapi-serializer/blob/master/test/serializer.js#L198
If you need a dynamic meta for a relationship, it was already implemented: https://github.com/SeyZ/jsonapi-serializer/blob/master/test/serializer.js#L1549
I think it’s fixed this issue, right? @bradbumbalough Hope you will come back here 👍 💃
This was a requirement for my use case. Ended up switching to https://github.com/kutlerskaggs/json-api-ify as they provide a somewhat dynamic meta option.