Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created a 'generic' serialize method, useful to use with web sockets. #15

Open
wants to merge 35 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
8abff87
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
1e68a3a
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
610d202
fix for web sockets not going
oiramalli Jul 21, 2016
23bfdc0
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
6065732
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
18dc298
fix for web sockets not going
oiramalli Jul 21, 2016
d3e7317
Merge branch 'generalSerializer' of https://github.com/oiramalli/sail…
oiramalli Jul 22, 2016
a832828
Cleaning up files
oiramalli Jul 22, 2016
f911673
Some more cleanup
oiramalli Jul 22, 2016
670e70a
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
a39ca95
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
66a7511
fix for web sockets not going
oiramalli Jul 21, 2016
aafc544
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
74a11e7
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
ebc65e5
Cleaning up files
oiramalli Jul 22, 2016
00a9216
Some more cleanup
oiramalli Jul 22, 2016
17c219f
Merge branch 'generalSerializer' of https://github.com/oiramalli/sail…
oiramalli Jul 22, 2016
39502f3
Some more cleanup...
oiramalli Jul 22, 2016
310fd23
Some more cleanup...
oiramalli Jul 22, 2016
8921274
Some more cleanup...
oiramalli Jul 22, 2016
18dd697
wait for normalizePayload to call next()
oiramalli Jul 26, 2016
00fd1fa
Serializer
oiramalli Dec 8, 2016
4e5dafd
Code cleanup
oiramalli Feb 8, 2017
39acb87
Some changes on serializer
oiramalli Feb 8, 2017
c674306
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
fb203e0
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
30c2afc
fix for web sockets not going
oiramalli Jul 21, 2016
af50ac4
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
a63972d
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
dc32182
Cleaning up files
oiramalli Jul 22, 2016
81e9997
Some more cleanup
oiramalli Jul 22, 2016
b7c6ef6
Created a serialaze 'generic' method.
oiramalli Jul 21, 2016
15d00b3
fix to to override the input on the config/jsonapi.js file
oiramalli Jul 21, 2016
acbdc08
Merge branch 'generalSerializer' of https://github.com/oiramalli/sail…
oiramalli Feb 8, 2017
f345004
Removing extra spaces
oiramalli Feb 8, 2017
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,19 @@ This is a [Sails JS](http://sailsjs.org) hook for creating an API which conforms

Just lift your app as normal, and your api responses will be formatted in accordance with [jsonapi.org](http://jsonapi.org/format/).

If you need to serialize data for other reasons (eg. send data trough sockets), you can use the serializeData method like this `serializedData = sails.hooks.jsonapi.serializeData(model,data);`.
This method takes 2 arguments
* *model:* The name of the model that you wish to serialize ('model' must be defined on the sails models).
* *data:* The data to be serialized.

#### Options
Create a `jsonapi.js` file inside the `config/` directory of your app, and you can set the following options:

| Option | Default | Description |
|---------------|:---------:|---------------|
| `compoundDoc` | `true` | When set to 'true' (default), response will be a [compound document](http://jsonapi.org/format/#document-compound-documents) including related resources. |
| `keyForAttribute` | `dash-case` | A function or string to customize attributes. Functions are passed the attribute as a single argument and expect a string to be returned. Strings are aliases for inbuilt functions for common case conversions. Options include: dash-case (default), lisp-case, spinal-case, kebab-case, underscore_case, snake_case, camelCase, CamelCase. |
| `pluralizeType` | `true` | When set to 'true' (default), the type is pluralized. |

### Known Limitations

Expand All @@ -46,4 +53,4 @@ This is unfinished. So far, the following are not yet implemented:
- [ ] Updating relationships
- [ ] Deleting relationships

There may be more. Please submit issue reports. Or better yet, pull requests.
There may be more. Please submit issue reports. Or better yet, pull requests.
13 changes: 11 additions & 2 deletions lib/hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

module.exports = function jsonApiHook(sails) {
var moduleUtils = require('./utils/module-utils');
var serializer = require('./serializer');
var _ = require('lodash');
var normalizeQueryParams = require('./requests/query-params');
var normalizePayload = require('./requests/payload');
Expand All @@ -14,7 +15,7 @@ module.exports = function jsonApiHook(sails) {
* @param {Function} next [description]
* @api private
*/
var addResponseMethods = function (req, res) {
function addResponseMethods(req, res) {
// Attach custom responses to `res` object
// Provide access to `req` and `res` in each of their `this` contexts.
_.each(sails.middleware.jsonapi.responses, function eachMethod(responseFn, name) {
Expand All @@ -24,7 +25,7 @@ module.exports = function jsonApiHook(sails) {
res: res,
});
});
};
}

return {

Expand All @@ -46,6 +47,10 @@ module.exports = function jsonApiHook(sails) {
});
},

serializeData: function (type, data) {
return serializer(type, data);
},

/**
* Shadow route bindings
* @type {Object}
Expand All @@ -54,19 +59,23 @@ module.exports = function jsonApiHook(sails) {
before: {

'all /*': function (req, res, next) {
if (req.isSocket) return next();
addResponseMethods(req, res);
next();
},

'GET /*': function (req, res, next) {
if (req.isSocket) return next();
addResponseMethods(req, res);
normalizeQueryParams(req, res);
next();
},

'POST /*': function (req, res, next) {
if (req.isSocket) return next();
addResponseMethods(req, res);
normalizePayload(req, next);
next();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There shouldn't be a call to next here. Has to wait for normalizePayload and therefore that one should call next. After removing this line (and ignoring still present coding stile issues) all tests passed for 8921274.

}
}
}
Expand Down
12 changes: 8 additions & 4 deletions lib/responses/json.js → lib/responses/ok.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ function normalizeResArgs( args ) {
};
if (isNumeric(args[0])) {
return {
statusCode: args[0],
statusCode: args[0],
other: args[1]
};
}
else return {
statusCode: args[1],
statusCode: args[1],
other: args[0]
};
}
Expand Down Expand Up @@ -62,7 +62,9 @@ module.exports = function json() {
sails.log.verbose('[jsonapi] modelName ::', modelName);
Model = sails.models[modelName];
opts = {
attributes: modelUtils.getAttributes(Model)
attributes: modelUtils.getAttributes(Model),
keyForAttribute: sails.config.jsonapi.keyForAttribute,
pluralizeType: sails.config.jsonapi.pluralizeType
};
// Add related model data
relationships = modelUtils.getRelationships(req);
Expand All @@ -73,7 +75,9 @@ module.exports = function json() {
Model = sails.models[collection];
// Related model attributes
opts[alias] = {
attributes: modelUtils.getOwnAttributes(Model)
attributes: modelUtils.getOwnAttributes(Model),
keyForAttribute: sails.config.jsonapi.keyForAttribute,
pluralizeType: sails.config.jsonapi.pluralizeType
};
// add models as relationships
if (modelUtils.isPopulatedRelationship(data, relationship)) {
Expand Down
37 changes: 37 additions & 0 deletions lib/serializer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const JSONAPISerializer = require('jsonapi-serializer').Serializer;

module.exports = function (modelName, data) {
let sails = this.req._sails;
let sailsModel = sails.models[modelName];
try {
if (!sailsModel || typeof sailsModel === 'undefined') {
throw new Error(`Looks like the model '${modelName}', does not exist.`);
}
} catch (err) {
// throw 1;
console.error(err);
return {};
}

let attributes = [];
Object.keys(sailsModel.definition).forEach(function (key) {
if (!sailsModel.definition[key].primaryKey && !sailsModel.definition[key].alias) {
attributes.push(key);
}
});
let Serializer = new JSONAPISerializer(modelName, {
attributes,
keyForAttribute: sails.config.jsonapi.keyForAttribute,
pluralizeType : sails.config.jsonapi.pluralizeType
});
try {
data = JSON.parse(JSON.stringify(data));
return Serializer.serialize(data);
} catch (err) {
console.error(`Unable to parse '${data}' for model '${modelName}', rerurning empty object \n
Attributes: ${attributes}`);
return {};
}
};
8 changes: 7 additions & 1 deletion lib/utils/norm-utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
'use strict';

exports.normalizeData = function (data) {
return JSON.parse(JSON.stringify(data));
try {
data = JSON.parse(JSON.stringify(data));
return data;
} catch (err) {
console.error(`Unable to parse '${data}', returning empty object`);
return {};
}
};
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
"url": "https://github.com/IanVS/sails-hook-jsonapi"
},
"dependencies": {
"jsonapi-serializer": "^3.2.0",
"lodash": "^4.5.0",
"pluralize": "^1.1.2",
"jsonapi-serializer": "^3.2.1",
"lodash": "^4.13.1",
"pluralize": "^1.2.1",
"sails-build-dictionary": "^0.10.1"
},
"devDependencies": {
Expand Down