olosegres/jsona

case change of property names

pelted opened this issue · 3 comments

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

@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(),
});

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!

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