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

case change of property names #1

Closed
pelted opened this issue Jun 29, 2017 · 3 comments
Closed

case change of property names #1

pelted opened this issue Jun 29, 2017 · 3 comments

Comments

@pelted
Copy link

pelted commented Jun 29, 2017

Am I missing a way of changing property names from kebab-case to camelCase and back again when serializing and deserializing?

@olosegres
Copy link
Owner

@pelted, It's possible with custom property mappers:

import Jsona, {ModelPropertiesMapper, JsonPropertiesMapper} from 'jsona';

class MyModelPropertiesMapper extends ModelPropertiesMapper {
    getAttributes(model) {
        const camelCasedAttributes = super.getAttributes(model);
        const cebabAttributes = {};
        Object.keys(camelCasedAttributes).forEach((name) => {
            const cebabName = name.replace(/([a-z][A-Z])/g, function (g) { return g[0] + '-' + g[1].toLowerCase() });
            cebabAttributes[cebabName] = camelCasedAttributes[name];
        });
        return cebabAttributes;
    }
}

class MyJsonPropertiesMapper extends JsonPropertiesMapper {
    setAttributes(model, attributes) {
        Object.keys(attributes).forEach((propName) => {
            const camelName = propName.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
            model[camelName] = attributes[propName];
        });
    }
}

const dataFormatter = new Jsona({
    modelPropertiesMapper: new MyModelPropertiesMapper(),
    jsonPropertiesMapper: new MyJsonPropertiesMapper(),
});

@joanlopez
Copy link

Hi @olosegres,

The solution proposed is not working well for me. This works for the first-level attributes, however, it does not work with the nested attributes (for example, with the attributes within the includes), what IMHO is essential as this library is intended for JSONAPI.

Any suggestion?

Thanks!

@olosegres
Copy link
Owner

Hi @joanlopez and @pelted

I have been added switchCasePropertyMappers.ts, it works with all level attributes (see tests)
7eac4b6

It's available since version 1.1.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants