compile-json-stringify
compile-json-stringify copied to clipboard
[Feature Request]: Default option?
Hi @nwoltman
Thanks for such a nice tool.
const cjs = compileJsonStringify({
type: 'object',
properties: {
status: { type: 'string' },
message: { type: 'string', default: 'OK' }, // <-- Default does not work
data: {
type: 'object',
properties: {
user: {
type: 'object',
properties: { id: { type: 'string' }, name: { type: 'string' } }
}
}
}
}
});
const data = {
status: 'success',
data: { user: { id: 'uuid', name: 'John' } }
};
cjs(data) // {"status":"success","data":{"user":{"id":"uuid","name":"John"}}}
Is there any way to get default work? Thanks
Hi @dalisoft, I'm glad you're finding the module useful. The default option simply isn't implemented. If you wanted to you could try implementing it, but adding that feature comes with some hard decisions. If the default option were implemented, either:
- It wouldn't work with the
additionalPropertiesoption, or compileJsonStringifywould have to do a bunch of extra work merging in the default properties when theadditionalPropertiesoption istrue, which doesn't really fit in with the purpose of this module. That additional work might also be slower than setting the defaults yourself before usingcompileJsonStringifyto stringify the object.
@nwoltman Thanks for reply.
I really want use this library as fast serializer to my node.js framework, but seems there some cons and a lot of users really does want use default property
Being able to set defaults sounds useful enough that I'd accept a PR that adds the default property. Alternatively, you could try running the data through Ajv before using this library for serialization. That should work since the schema format that this library uses should be the same as Ajv, and I wouldn't expect Ajv to add much overhead.