objection-to-json
v1.0.2
Published
Package to map Objection.js result models to JSON-able objects according to a provided schema
Downloads
3
Maintainers
Readme
objection-to-json
Package to map objection.js result models to JSON-able objects according to a provided schema
Install
npm install --save objection-to-json
Usage
const processResultToJSON = require('objection-to-json');
// Build object containing Objection.js models of interest, keyed under their class name
const models = {
Book,
Author
};
const schema = {
Book: {
include: ['@all'], // include all fields
exclude: '@pk' // exclude primary key field
},
Author: {
include: ['name', '@fk'] // exclude foreign key fields
},
options: {
excludeKeyIfNull: false // Keep fields even if they have a null value (default)
}
};
const results = Book.query().eager('authors');
const resultJson = processResultToJSON(results, schema, models);
This results in a result like:
resultJson === [
{
title: 'A Tale of Two Cities',
category: 'fiction',
authors: [
{ id: 102, name: 'Dickens, Charles' }
]
},
{
'title': 'The Grapes of Wrath',
category: 'fiction',
authors: [
{ id: 204, name: 'Steinbeck, John' }
]
},
{
title: 'Good Omens',
category: 'fiction',
authors: [
{ id: 23, name: 'Pratchett, Terry'},
{ id: 24, name: 'Gaiman, Neil' }
]
}
];