Monday, 19 August 2019

Loopback 4 how to create a Model that represents nested objects

TL;DR
How do I create a Model that include nested Objects without creating a new Model for every property that is of type Object?

New to LB4 & Typescript so apologies if this is an obv question. I want to create a Model which represents a Response that includes a nested Object for my endpoint. Here is a sample response:

{
  "result": {
    "prop1": "blah blah",
    "prop2": {
      "subProp": {
        "subSubProp": "blah blah"
      }
    }
  }
}

Problem I have is representing the nested object inside of my Model. Ideally I would do something like this:

@model()
export class MyResponseModel extends Model {
  @property({
    type: 'object'
  })
  result: {
    prop1: string,
    prop2: {
      subProp: {
        subSubProp: string
      }
    }
  }
}

Then in my controller I would set this as the response type:

@post('/my-endpoint', {
  responses: {
    ...,
    schema: {
      'x-ts-type': MyResponseModel,
    }
  }
})
async post(): Promise<MyResponseModel>{...}

The only way I have got this working so far is creating a Model for every nested object i.e. a Model for "result", another for "prop2" and another for "subProp" which doesn't feel is the right way to implement this?

Same q asked for LB3 but doesn't answer it for LB4: loopback model with object

Asked in google group with no answer: https://groups.google.com/forum/?nomobile=true#!topic/loopbackjs/AKgZT6V-pCc

Thanks in advance!



from Loopback 4 how to create a Model that represents nested objects

No comments:

Post a Comment