Skip to content

Instantly share code, notes, and snippets.

@davidlondono
Created August 30, 2016 15:09
Show Gist options
  • Save davidlondono/f46e74b87ca0a392aacb165669fe316e to your computer and use it in GitHub Desktop.
Save davidlondono/f46e74b87ca0a392aacb165669fe316e to your computer and use it in GitHub Desktop.
/**
* Created by david on 8/29/16.
*/
import mongoose from "mongoose";
import _ from "lodash"
import {Serializer as JSONAPISerializer} from "jsonapi-serializer";
import Inflected from "inflected"
const mongooseIdRef = (__, item) => {
// item could be an MongoDB ObjectId, a MongoDB BSON type with toHexString
// function, a MongoDB populated Object with id attribute or a plain String
if (item instanceof mongoose.Types.ObjectId) {
return item.toString();
} else if (item && _.isFunction(item.toHexString)) {
return item;
} else if (item && item.id) {
return item.id;
}
return item;
};
const PluginApi = function PluginApi(schema) {
const options = schema.options;
if (!options || !options.jsonApi) {
return;
}
const jsonApiOptions = options.jsonApi;
const collectionName = jsonApiOptions.collectionName || '';
const collectionPlural = Inflected.pluralize(collectionName);
//options for serializer
const obj = {
topLevelLinks : {
self: (body) => `/${collectionPlural}${(_.isArray(body) || !body.id) ? '' : `/${body.id}`}`
},
dataLinks : {
self: (order) => `/${collectionPlural}/${order.id}`
},
pluralizeType : false
};
obj.attributes = jsonApiOptions.attributes;
const serializerObj = function() {
const references = jsonApiOptions.references;
if (references) {
references.forEach(function (refModel) {
const status = schema.paths[refModel];
const serializerModel = {
ref: mongooseIdRef
};
const modelName = status.options.ref;
if (modelName) {
const model = mongoose.model(modelName);
serializerModel.attributes = model.attributes;
}
obj[refModel] = serializerModel;
console.log(status,status.model);
})
}
return obj;
};
schema.statics.serialize = (body) => {
const Serializer = new JSONAPISerializer(collectionName, serializerObj());
return Serializer.serialize(body);
};
schema.methods.serialize = function () {
return this.constructor.Serialize(this);
}
};
export {PluginApi}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment