Search code examples
javascriptswaggerloopbackjs

Creating a LoopBack model with a complex data-type


I'm trying to create a model in LoopBack API, the model's JSON widget.json file is:

    {
    "name": "widget",
    "plural": "widgets",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
      "validateUpsert": true
    },
    "properties": {
      "id": {
        "type": "string",
        "default": null
      },
      "projectId": {
        "type": "string",
        "default": null
      },  
      "clientId":{
        "type":"string",
        "required":false
      },
      "createdOn": {
        "type": "date",
        "defaultFn": "now"
      },
      "updatedOn": {
        "type": "date",
        "defaultFn": "now"
      },
      "deletedOn": {
        "type": "date",
        "default": null
      },
      "type":{
        "type": "string",
        "default": null
      },
      "version":{
        "type": "string",
        "default":null 
      },
      "dataSource":{
        "type": "dataSource"
      }
    },
    "validations": [],
    "acls": [],
    "methods": {},
    "mixins": {
      "Timestamps": true
    }
  }

The problem is that the property:

dataSource

is an object, I tried to declare it in the widget.js file:

'use strict';

const ModelBuilder = require('loopback-datasource-juggler').ModelBuilder;
const modelBuilder = new ModelBuilder();

const dataSource = modelBuilder.define('dataSource', {
  endpoint: String,
  params: [String],
  query: String,
});

When I run the code, I'm getting this error:

Swagger: skipping unknown type "dataSource".

I also tried to find a way to decalare that type as a definition in the same way we do when declaring a swagger file, but I couldn't find!

any ideas or suggestions?


Solution

  • I solved it by declaring the dataSource as the following:

    "dataSource":{
      "type": {
          "endpoint": "string",
          "params": ["string"],
          "query": "string"
      }
    }