Search code examples
loopbackjsstronglooploopback4

How can I work with Nested Objects in Loopback 4 using the cli b4 model command


I'm working with deep nested objects that I need to model for using lb4. Any chance I can get help with this sample JSON code?

{ "cardAcceptor": { "address": { "city": "Foster City", "country": "RU", "county": "San Mateo", "state": "CA", "zipCode": "94404" }, "idCode": "ABCD1234ABCD123", "name": "ABCD", "terminalId": "ABCD1234" }, "destinationCurrencyCode": "840", "markUpRate": "1", "retrievalReferenceNumber": "201010101031", "sourceAmount": "100", "sourceCurrencyCode": "643", "systemsTraceAuditNumber": "350421" }


Solution

  • You can create separate Models for the nested objects,

    for example for above data structure

    You can have something like

    export class CardAcceptor extends Address {
    
      @property({
        type: 'string',
        required: true,
      })
      address: string;
    
      @property({
        type: 'string',
        required: true,
      })
      idCode: string
    
      @property({
        type: 'string',
        required: true,
      })
      name: string;
    
      @property({
        type: 'string',
        required: true,
      })
      terminalId: string;
    
      constructor(data?: Partial<CardAcceptor>) {
        super(data);
      }
    }
    
    export class Address extends Entity {
    
      @property({
        type: 'string',
        required: true,
      })
      city: string;
    
      @property({
        type: 'string',
        required: true,
      })
      country: string
    
      @property({
        type: 'string',
        required: true,
      })
      county: string;
    
      @property({
        type: 'string',
        required: true,
      })
      state: string;
    
    
      @property({
        type: 'boolean',
        required: true,
      })
      zipCode: boolean;
    
      constructor(data?: Partial<Address>) {
        super(data);
      }
    }
    
    
    export class BaseModel extends CardAcceptor {
    
    
      @property.array(CardAcceptor)
      cardAcceptor: CardAcceptor;
    
      @property({
        type: 'string',
        required: true,
      })
      destinationCurrencyCode: string;
    
      @property({
        type: 'string',
        required: true,
      })
      markUpRate: string
    
      @property({
        type: 'string',
        required: true,
      })
      retrievalReferenceNumber: string;
    
      @property({
        type: 'string',
        required: true,
      })
      sourceAmount: string;
    
    
      @property({
        type: 'boolean',
        required: true,
      })
      sourceCurrencyCode: boolean;
    
      @property({
        type: 'array',
        itemType: 'string',
        default: [],
      })
      systemsTraceAuditNumber?: string[];
    
    
      constructor(data?: Partial<Game>) {
        super(data);
      }
    }
    
    

    Hopefully, this helps. Thanks