prismake / typegql

Create GraphQL schema with TypeScript classes.
https://prismake.github.io/typegql/
MIT License
423 stars 21 forks source link

[question] returning an instance of a class #44

Closed cgatian closed 6 years ago

cgatian commented 6 years ago

Expected value of type "User" but got: [object Object]

  @Query()
    hello(): User {
      return {
        name: 'Dave'
      };
    }

Scratching my head on this. I think I've narrowed it down to the function expects an actual instance of the User object and not an anonymous object. Is there a better way to do this?

If an instance of the class does need to be returned do you need copy properties into an instance like below to make sure the types are correct?

Object.assign(new User(), userShapeFromDb)
pie6k commented 6 years ago

hey,

TLDR; yes, you should assign properties yourself.

However - it's up to you where and how you create your instance.

You may have user class that takes user id in constructor new User(42); and assign it to itself in constructor, and then uses this id lazyli in resolvers etc.

Could you describe your use-case a bit more? Seems you're using some kind of ORM for connecting your database.

You can try http://typeorm.io as it creates such instances automatically - here is typegql example of integrating it with such ORM: https://github.com/prismake/typegql/tree/master/examples/typeorm-basic-integration

cgatian commented 6 years ago

Thanks for the super fast response!

No, just general question on how I should be instantiating the objects. It was something I struggled with and the examples/docs didn't mention you cannot return just the shape.

I looked through tslint/tsconfig and didnt see anything that allowed you to suppress type coercion from object litterals. That would be ideal.

pie6k commented 6 years ago

Technically we could implement feature that would convert such shape to class instance under the hood with Object.assign, but it could lead to some unexpected results (eg. When constructor has required, custom arguments).

Some more reasoning behind this that could help you understand such approach.

Imagine your user class has method isOld that returns true if age is more than 100.

If you return instance - it'll have this method. Simple shape object does not so nested query would break.

cgatian commented 6 years ago

Just getting my feet wet in this, and my example was contrived. Your points are valid. Thank you for your response.