Skip to content

Added ability to override schema options, added tests, updated docs #96

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

Merged
merged 2 commits into from
Dec 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,23 @@ Serializer.serializeAsync('article', data, 'default', {count: 2}, true)
});
```

#### Override schema options

On each individual call to `serialize` or `serializeAsync`, there is an parameter to override the options of any registered type. For example on a call to serialize, if a whitelist was not defined on the registered schema options, a whitelist (or any other options) for that type can be provided. This parameter is an object, where the key are the registered type names, and the values are the objects to override the registered schema.

In the following example, only the attribute `name` will be serialized on the article, and if there is a relationship for `person`, it will be serialized with `camelCase` even if the registered schema has a different value.
```
const result = Serializer.serialize('article', data, 'default', {count: 2}, true), {
article: {
whitelist: ['name']
},
person: {
convertCase: 'camelCase'
}
};
```


Some others examples are available in [tests folders](https://github.com/danivek/json-api-serializer/blob/master/test/)

### Deserialize
Expand Down
119 changes: 101 additions & 18 deletions lib/JSONAPISerializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ module.exports = class JSONAPISerializer {
* @param {string|object} [schema='default'] resource's schema name.
* @param {object} [extraData] additional data that can be used in topLevelMeta options.
* @param {boolean} [excludeData] boolean that can be set to exclude the `data` property in serialized data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {object} serialized data.
*/
serialize(type, data, schema, extraData, excludeData) {
serialize(type, data, schema, extraData, excludeData, overrideSchemaOptions = {}) {
// Support optional arguments (schema)
if (arguments.length === 3) {
if (typeof schema === 'object') {
Expand Down Expand Up @@ -108,14 +109,33 @@ module.exports = class JSONAPISerializer {
options = this.schemas[type][schema];
}

const overrideType = isDynamicType ? type.type : type;
if (overrideSchemaOptions[overrideType]) {
// Merge default (registered) options and extra options into new options object
options = { ...options, ...overrideSchemaOptions[overrideType] };
}

let dataProperty;

if (excludeData) {
dataProperty = undefined;
} else if (isDynamicType) {
dataProperty = this.serializeMixedResource(options, data, included, extraData);
dataProperty = this.serializeMixedResource(
options,
data,
included,
extraData,
overrideSchemaOptions
);
} else {
dataProperty = this.serializeResource(type, data, options, included, extraData);
dataProperty = this.serializeResource(
type,
data,
options,
included,
extraData,
overrideSchemaOptions
);
}

return {
Expand All @@ -138,9 +158,10 @@ module.exports = class JSONAPISerializer {
* @param {string} [schema='default'] resource's schema name.
* @param {object} [extraData] additional data that can be used in topLevelMeta options.
* @param {boolean} [excludeData] boolean that can be set to exclude the `data` property in serialized data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {Promise} resolves with serialized data.
*/
serializeAsync(type, data, schema, extraData, excludeData) {
serializeAsync(type, data, schema, extraData, excludeData, overrideSchemaOptions = {}) {
// Support optional arguments (schema)
if (arguments.length === 3) {
if (typeof schema === 'object') {
Expand Down Expand Up @@ -175,6 +196,12 @@ module.exports = class JSONAPISerializer {
options = this.schemas[type][schema];
}

const overrideType = isDynamicType ? type.type : type;
if (overrideSchemaOptions[overrideType]) {
// Merge default (registered) options and extra options into new options object
options = { ...options, ...overrideSchemaOptions[overrideType] };
}

return new Promise((resolve, reject) => {
/**
* Non-blocking serialization using the immediate queue.
Expand All @@ -193,8 +220,21 @@ module.exports = class JSONAPISerializer {
try {
// Serialize a single item of the data-array.
const serializedItem = isDynamicType
? that.serializeMixedResource(type, arrayData[i], included, extraData)
: that.serializeResource(type, arrayData[i], options, included, extraData);
? that.serializeMixedResource(
type,
arrayData[i],
included,
extraData,
overrideSchemaOptions
)
: that.serializeResource(
type,
arrayData[i],
options,
included,
extraData,
overrideSchemaOptions
);

if (serializedItem !== null) {
serializedData.push(serializedItem);
Expand Down Expand Up @@ -525,23 +565,32 @@ module.exports = class JSONAPISerializer {
* @param {object} options resource's configuration options.
* @param {Map<string, object>} [included] Included resources.
* @param {object} [extraData] additional data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {object|object[]} serialized data.
*/
serializeResource(type, data, options, included, extraData) {
serializeResource(type, data, options, included, extraData, overrideSchemaOptions = {}) {
if (isEmpty(data)) {
// Return [] or null
return Array.isArray(data) ? data : null;
}

if (Array.isArray(data)) {
return data.map(d => this.serializeResource(type, d, options, included, extraData));
return data.map(d =>
this.serializeResource(type, d, options, included, extraData, overrideSchemaOptions)
);
}

return {
type,
id: data[options.id] ? data[options.id].toString() : undefined,
attributes: this.serializeAttributes(data, options),
relationships: this.serializeRelationships(data, options, included, extraData),
relationships: this.serializeRelationships(
data,
options,
included,
extraData,
overrideSchemaOptions
),
meta: this.processOptionsValues(data, extraData, options.meta),
links: this.processOptionsValues(data, extraData, options.links)
};
Expand All @@ -557,16 +606,19 @@ module.exports = class JSONAPISerializer {
* @param {object|object[]} data input data.
* @param {Map<string, object>} [included] Included resources.
* @param {object} [extraData] additional data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {object|object[]} serialized data.
*/
serializeMixedResource(typeOption, data, included, extraData) {
serializeMixedResource(typeOption, data, included, extraData, overrideSchemaOptions = {}) {
if (isEmpty(data)) {
// Return [] or null
return Array.isArray(data) ? data : null;
}

if (Array.isArray(data)) {
return data.map(d => this.serializeMixedResource(typeOption, d, included, extraData));
return data.map(d =>
this.serializeMixedResource(typeOption, d, included, extraData, overrideSchemaOptions)
);
}

// Resolve type from data (can be a string or a function deriving a type-string from each data-item)
Expand All @@ -581,7 +633,13 @@ module.exports = class JSONAPISerializer {
throw new Error(`No type registered for ${type}`);
}

return this.serializeResource(type, data, this.schemas[type].default, included, extraData);
let options = this.schemas[type].default;
if (overrideSchemaOptions[type]) {
// Merge default (registered) options and extra options into new options object
options = { ...options, ...overrideSchemaOptions[type] };
}

return this.serializeResource(type, data, options, included, extraData, overrideSchemaOptions);
}

/**
Expand Down Expand Up @@ -633,9 +691,10 @@ module.exports = class JSONAPISerializer {
* @param {object} options resource's configuration options.
* @param {Map<string, object>} [included] Included resources.
* @param {object} [extraData] additional data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {object} serialized relationships.
*/
serializeRelationships(data, options, included, extraData) {
serializeRelationships(data, options, included, extraData, overrideSchemaOptions = {}) {
const serializedRelationships = {};

Object.keys(options.relationships).forEach(relationship => {
Expand All @@ -656,7 +715,8 @@ module.exports = class JSONAPISerializer {
get(data, relationshipKey),
included,
data,
extraData
extraData,
overrideSchemaOptions
)
};

Expand Down Expand Up @@ -689,9 +749,18 @@ module.exports = class JSONAPISerializer {
* @param {Map<string, object>} [included] Included resources.
* @param {object} [data] the entire resource's data.
* @param {object} [extraData] additional data.
* @param {object} [overrideSchemaOptions=] additional schema options, a map of types with options to override
* @returns {object|object[]} serialized relationship data.
*/
serializeRelationship(rType, rSchema, rData, included, data, extraData) {
serializeRelationship(
rType,
rSchema,
rData,
included,
data,
extraData,
overrideSchemaOptions = {}
) {
included = included || new Map();
const schema = rSchema || 'default';

Expand All @@ -707,7 +776,15 @@ module.exports = class JSONAPISerializer {

if (Array.isArray(rData)) {
return rData.map(d =>
this.serializeRelationship(rType, schema, d, included, data, extraData)
this.serializeRelationship(
rType,
schema,
d,
included,
data,
extraData,
overrideSchemaOptions
)
);
}

Expand All @@ -726,7 +803,13 @@ module.exports = class JSONAPISerializer {
throw new Error(`No schema "${schema}" registered for type "${type}"`);
}

const rOptions = this.schemas[type][schema];
let rOptions = this.schemas[type][schema];

if (overrideSchemaOptions[type]) {
// Merge default (registered) options and extra options into new options object
rOptions = { ...rOptions, ...overrideSchemaOptions[type] };
}

const serializedRelationship = { type };

// Support for unpopulated relationships (an id, or array of ids)
Expand All @@ -738,7 +821,7 @@ module.exports = class JSONAPISerializer {
if (!(Object.keys(rData).length === 1 && rData[rOptions.id])) {
included.set(
`${type}-${serializedRelationship.id}`,
this.serializeResource(type, rData, rOptions, included, extraData)
this.serializeResource(type, rData, rOptions, included, extraData, overrideSchemaOptions)
);
}
}
Expand Down
Loading