objection-to-json

1.0.2 • Public • Published

objection-to-json

Package to map objection.js result models to JSON-able objects according to a provided schema

NPM Version Linux Build Coverage

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' }
    ]
  }
];

License

MIT

Package Sidebar

Install

npm i objection-to-json

Weekly Downloads

0

Version

1.0.2

License

MIT

Unpacked Size

19.2 kB

Total Files

7

Last publish

Collaborators

  • jones.tristand