loopbackio / loopback-next

LoopBack makes it easy to build modern API applications that require complex integrations.
https://loopback.io
Other
4.95k stars 1.07k forks source link

How to use property attributes at the belongsTo decorator? #2135

Closed nebulon42 closed 5 years ago

nebulon42 commented 5 years ago

Description / Steps to reproduce / Feature proposal

I'd like to mark a model property that is decorated with @belongsTo as required. Normally I would do that by using the @property decorator. I can't use that since it is implicitly called by the @belongsTo decorator. From looking at https://github.com/strongloop/loopback-next/blob/master/packages/repository/src/relations/belongs-to/belongs-to.decorator.ts#L21-L24 I thought I could use something like

@belongsTo(
  () => User,
  {},
  {
    required: true
  }
)

You also use something similar in one test at https://github.com/strongloop/loopback-next/blob/master/packages/repository/test/unit/decorator/model-and-relation.decorator.unit.ts#L97-L104.

Current Behavior

Currently it gives me error TS2554: Expected 1-2 arguments, but got 3.. Not sure if I do something wrong.

Expected Behavior

I'm able to use property attributes on the @belongsTo decorator.

dhmlau commented 5 years ago

@nebulon42 , sorry about the late reply.
Looking at the BelongsToDefinition, it doesn't seem like required is the correct property name. https://github.com/strongloop/loopback-next/blob/master/packages/repository/src/relations/relation.types.ts.

If you want to make that as required, you can:

  @belongsTo(() => User)
  userId: number;  //if it's optional, it would be userId?:number.

Hope it helps.

dhmlau commented 5 years ago

@nebulon42, I'd like to follow up with you on this issue. Did my comment answer your question? If so, I'd like to close it. Thanks.

nebulon42 commented 5 years ago

Looks like there was a misunderstanding on my part because I'm not very familiar with TypeScript. Seems like you answered my question, thanks. I close here. If I still have troubles with it I'll follow up.

SandroMoretti commented 3 years ago

Hi @dhmlau. Making userId: and not userId?: don't make the field NOT NULLABLE in relational database when created by lb4 migration.

I tested it on postgresql and would be nice if we have some way to do not nullable like the propertie @required of normal fields.