Skip to content

1.2. Creating Models

Arnav Gupta edited this page Feb 5, 2018 · 3 revisions

Define a Model

Define a model, and then populate the examples

const jsonApi = require('jagapi')
const sqlHandler = require('../handlers/sequelize').createHandler()
const Joi = jsonApi.Joi


jsonApi.define({
    namespace: 'json:api',
    resource: 'users',
    handlers: sqlHandler,
    primaryKey: 'autoincrement',
    attributes: {
        id: Joi.string(),
        name: Joi.string().required()
    },
    examples: [
        {type: 'users', name: 'Arnav'},
        {type: 'users', name: 'Prateek'},
        {type: 'users', name: 'Deepak'},
        {type: 'users', name: 'Rishab'},
        {type: 'users', name: 'Garima'}
    ]
})

/**
 * @param force set to true only for dev mode (drops tables)
 */
sqlHandler.populate({force: true})

Models With Relationships

Definition

Models could have relationships, use Joi.one or Joi.many for that

const jsonApi = require('jagapi')
const sqlHandler = require('../handlers/sequelize').createHandler()
const Joi = jsonApi.Joi


jsonApi.define({
    namespace: 'json:api',
    resource: 'tasks',
    handlers: sqlHandler,
    primaryKey: 'autoincrement',
    attributes: {
        id: Joi.string(),
        title: Joi.string().required(),
        description: Joi.string(),
        instances: Joi.number().integer().min(1).default(1),
        owner: Joi.one('users').uidType('autoincrement')
    },
    examples: [
        {
            type: 'tasks',
            title: 'N-Queens Problem',
            description: 'Make a problem from N-Queens',
            instances: 2,
            owner: {
                id: '1',
                type: 'users'
            }
        },
        {
            type: 'tasks',
            title: 'Array 2-sum',
            description: 'Make a problem on Array 2-sum-K',
            instances: 2,
            owner: {
                id: '1',
                type: 'users'
            }
        },
        {
            type: 'tasks',
            title: 'Palindrome Subsequence',
            description: 'Make a question about finding palindromic subsequences',
            instances: 2,
            owner: {
                id: '2',
                type: 'users'
            }
        }
    ]
})


/**
 * @param force set to true only for dev mode (drops tables)
 */
sqlHandler.populate({force: true})

Even if we omit .uidType('autoincrement') it will still work but the DB will turn slower over time. This is because, if not uidType is given, we assume that the foreignKey column will have id type STRING