by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
  • May 30 08:32
    MichalLytek labeled #641
  • May 30 08:32
    MichalLytek labeled #641
  • May 30 08:32
    MichalLytek labeled #641
  • May 30 08:32
    MichalLytek closed #641
  • May 30 08:32
    MichalLytek commented #641
  • May 30 08:06
    Artimunor opened #641
  • May 29 07:58
    MichalLytek commented #640
  • May 29 07:53
    madmaxlax commented #640
  • May 29 07:26
    MichalLytek labeled #640
  • May 29 07:26
    MichalLytek labeled #640
  • May 29 07:26
    MichalLytek labeled #640
  • May 29 07:26
    MichalLytek closed #640
  • May 29 07:26
    MichalLytek commented #640
  • May 29 01:10
    RyannGalea commented #117
  • May 29 01:04
    RyannGalea commented #117
  • May 28 21:17
    madmaxlax opened #640
  • May 28 21:16
  • May 28 20:35
  • May 28 19:20
    MichalLytek commented #639
Liam Read
@LiamDotPro
import { Arg, Mutation, Query, Resolver } from "type-graphql";
import { Book } from "../models/Book";
import { CreateBookInput } from "../inputs/CreateBookInput";
import { UpdateBookInput } from "../inputs/UpdateBookInput";

@Resolver(of => Book)
export class BookResolver {
    @Query(() => [Book], { name: "getBooks" })
    books() {
        return Book.find();
    }

    @Query(returns => Book, { name: 'getBook' })
    book(@Arg("id") id: string) {
        return Book.findOne({ where: { id } });
    }

    @Mutation(returns => Book, { name: 'createBook' })
    async createBook(@Arg("data") data: CreateBookInput): Promise<Book> {
        const book = Book.create(data);
        await book.save();
        return book;
    }

    @Mutation(returns => Book, { name: 'updateBook' })
    async updateBook(@Arg("id") id: string, @Arg("data") data: UpdateBookInput): Promise<Book> {
        const book = await Book.findOne({ where: { id } });
        if (!book) throw new Error("Book not found!");
        Object.assign(book, data);
        await book.save();
        return book;
    }

    @Mutation(returns => Boolean, { name: "deleteBook" })
    async deleteBook(@Arg("id") id: string): Promise<boolean> {
        const book = await Book.findOne({ where: { id } });
        if (!book) throw new Error("Book not found!");
        await book.remove();
        return true;
    }
}
It will push to graph manager just fine but the codegen just complains about some annoymous operation..
DerpDays
@DerpDays
hey :)
is there anyway to annotate stuff in typegraphql?
for example explain a resolver's function
DerpDays
@DerpDays
never mind, found out how to
1 reply
bredar
@bredar

Hey! would like to use a promise inside a custom method decorator:

export function CheckACLSimple(fieldname: string, accessRight: string) {
    return createMethodDecorator(async ({ args }, next) => {
        const objectID = args[fieldname];

        // checks the state of the ACL on the database
        checkACL(objectID, accessRight, 123).then((checkResult) => {
            if (!checkResult) {
                throw new UnauthorizedError(); // Error('CheckAcl not ok')
            }
        });

        return next();
    });

But the error is not handled by anyone.

(node:44416) UnhandledPromiseRejectionWarning: Error: Access denied! You need to be authorized to perform this action!

How can I do this?

1 reply
Huyhq
@xfile129_twitter

Hi everybody, here is my code. I try to inject services inside the resolver class but ResourceService has a constructor and it doesn't work. How can I fix it?

//ResourceService.ts

@Service()
export class ResourceService<T> {
  constructor(protected resources: ModelType<T>) {}

  async getById(_id: ObjectId): Promise<T | null> {
    return this.resources.findById(_id);
  }
}

//UserService.ts

@Service()
export class UserService extends  ResourceService<User>{
  async getUserByRole() {}
}

//Resolver.ts

@Resolver(() => User) 
export class UserResolver {
  @Inject()
  private userService: UserService;

  @Query()
  protected async getUser() {
    // this.userService.getById();
    // this.userService.getUserByRole();
  }
}
6 replies
konuch
@konuch
Hello, I would like to ask if it's possible to apply @Authorized() decorator to specific fields of InputTypes. For example both regular user and admin have access to a given mutation, but only admin role can also use "restricted" property in their inputs. Thanks
5 replies
Ghost
@ghost~57521253c43b8c601976a704

hello, i am new on using aws appsync, I am building my first schema, what i am trying to do is to create the following table like Course and i want Topic and SubTopic as nested sub-documents is it possible to make this in schema level ? like so

type Course @model 
  @auth(rules: [{allow: owner, queries: null}]){
      id: ID!
      title: String!
     topics  {
           id: ID!
           title: String
           subTopics: {
                  id: ID!
                  title: String!
           } 
     }
}

and how to get all data using elastic search?

1 reply
Michael
@SWinja_gitlab
How can I get IP address of requester inside the mutation?
I've checked decorators and logged any data they provide to console but they do not include request or headers.
Is it ever possible using type-graphql library?
6 replies
AmrAnwar
@AmrAnwar
Hello everybody,
I'm trying to add globalMiddlewares, I followed the example in Github to
add ResolveTimeMiddleware like here:
globalMiddlewares: [ResolveTimeMiddleware]
once I add it here I get this error from all graphql requests even without adding @UseMiddleware():
"message": "Cannot read property 'prototype' of undefined",
7 replies
jjesudassbah
@jjesudassbah
How do i get the names of the fields the user is requesting in the resolver method?
1 reply
webdesign2be
@webdesign2be

Hi guys, I got stuck on a Custom Property.. :sweat_smile:

@ObjectType()
@InputType('InputProperties')
export class Properties {
  name: string
  value: string
}


@ObjectType()
@Entity("configurations")
export class Configuration extends BaseEntity {
  @Field(() => Int)
  @PrimaryGeneratedColumn()
  id: number;

  @Field()
  @Column("text")
  name: string;

  @Field()
  @Column("text")
  collection: string;

  @Field(() => [Properties])
  @Column("text")
  properties: Properties[];
}

UnhandledPromiseRejectionWarning: Error: Generating schema error
at Function.<anonymous> (/Users/kaos/Server/gql/server/node_modules/type-graphql/dist/schema/schema-generator.js:20:27)

No Idea how to solve it..

Troy Zarger
@tzarger
Maybe add @Field() on name and value properties in your Properties class?
webdesign2be
@webdesign2be
let me check that
Yes it worked... Thank you!
Matt Cushing
@cushmatt

Hey, so I'm running into some issues getting dependency injection from 'tsyringe' to work with Type-GraphQL and I was hoping I could get a little insight from anyone here. It seems that the instance isn't being made or I'm messing up somewhere and I'm always getting something similar to, "Cannot read property 'find' of undefined". Anyways, here's how I'm currently implementing it:

// index.ts
import { container } from 'tsyringe';
import { useContainer, ConnectionManager, createConnection } from 'typeorm';
import { buildSchema } from 'type-graphql';

const main = async () => {
    container.register<ConnectionManager>(ConnectionManager, {
        useFactory: instanceCachingFactory(() => new ConnectionManager()),
    });

    useContainer({
        get: someClass => container.resolve(someClass as any),
    });

....

    const schema = await buildSchema({
        resolvers: [SomethingResolver],
        container: { get: someClass => container.resolve(someClass as any) },
    });

....
// SomethingRepo.ts
import { EntityRepository, Repository } from 'typeorm';
import { Something } from '../entities/Something';

@EntityRepository(Something)
export class SomethingRepo extends Repository<Something> {
    async getSomethings() {
        return this.find();
    }
}
// SomethingResolver.ts
import { Resolver, Query } from 'type-graphql';
import { SomethingRepo } from '../repositories/SomethingRepo';
import { Something } from '../entities/Something';
import { injectable } from 'tsyringe';

@Resolver()
@injectable()
export class SomethingResolver {
    constructor(public: somethingRepo: SomethingRepo) {}

    @Query(() => [Something])
    async getSomethings(): Promise<Something[] | undefined> {
        return this.somethingRepo.getSomethings();
    }
}

I have gotten typedi to work just fine but it seems the project isn't being actively maintained anymore (same goes with injectorjs) and I saw an issue where the maintainer of type-graphql was mentioned and he had recommended tsyringe so I'm assuming he has gotten it working no problem with it and I'm just missing something somewhere. Anyways, I would really appreciate any help or advice.

Note: I apologize for any typos, I made up and threw the code together pretty quickly

4 replies
konuch
@konuch
Hello, is it possible for a resolver method parameter to have more decorators? For example a combination of @Arg() with @CustomDecorator, where CustomDecorator transforms the input. I tried this approach, and it seemed to work, but I noticed, that when using this decorator, also the 2nd parameter @Ctx() ctx: Context, gets the same value as userInput
Example:
  @Authorized(UserRoleEnum.ADMIN, UserRoleEnum.SUPER_USER)
  @Mutation(returns => User)
  async addUser(
    @Arg("user") @CustomDecorator() userInput: CreateUserInput,
    @Ctx() ctx: Context,
  ){
 // some code
}
2 replies
Karl Adler
@karladler
I just upgraded to GQL 15 and type-graphql 1rc2 and get this typings error. Does anybody know this?
src/server.ts:23:5 - error TS2322: Type '(typeof UserResolver | /*list of resolvers*/ )[]' is not assignable to type 'readonly [Function, ...Function[]] | [Function, ...Function[]] | readonly [string, ...string[]] | [string, ...string[]]'.
  Property '0' is missing in type '(typeof UserResolver | /*list of resolvers*/ )[]' but required in type '[string, ...string[]]'.

23     resolvers,
       ~~~~~~~~~

  node_modules/type-graphql/dist/utils/buildSchema.d.ts:10:5
    10     resolvers: NonEmptyArray<Function> | NonEmptyArray<string>;
           ~~~~~~~~~
    The expected type comes from property 'resolvers' which is declared here on type 'BuildSchemaOptions'
3 replies
Leo Hui
@leohxj
how to use type-graphql generate this nested query filed?
type User {
    firstname: String
    lastname: String
    tasks(status: Int): [Task]
}
type Task {
    id: String!
    name: String
}

type Query {
    user(department_id: String!): User!
}
6 replies
and useage :
{
  user(department_id: 5) {
    firstname
    lastname
    tasks(status: 2) {
      id
      name
    }
  }
}
Jonathan Tushman
@jtushman

Hi friends ... with

  @Column("jsonb", {
    nullable: true
  })
  traits: Record<string, any>

whats the best practice -- should the fields return string @Field(() => string) or leverage something like https://github.com/taion/graphql-type-json

10 replies
quanganhtran
@quanganhtran
I have some resolver that was not passed to buildSchema but is still available in the schema. is there some sort of auto registration or registration through dependencies mechanism? though it could also be something in user land that I missed
11 replies
bredar
@bredar

Sometimes, it's good enough to just get the primary key value of a referenced data instead of the full object. No join or subquery is needed. One solution seems to be to just export the same field twice.

    @Field(_type => SMObjectType)
    @ManyToOne(()=>ObjectType, (ObjectType: ObjectType)=>OBJECTTYPE.objects)
    @JoinColumn({ name: 'OBJECTTYPE' })
    objectTypeDetails?: SMObjectType;

    @Field()
    @Column('varchar', { name: 'OBJECTTYPE'})
    objectType: string;
`

I wonder if there is a better way to do this?

Mengkheang
@mengkheang_gitlab
how to make @Query resolver return optional type?
Mengkheang
@mengkheang_gitlab
image.png
@Query(() => UserType)
would be non-null in the schema
image.png
user(
id: String!
): User!
how to make return type optional?
1 reply
Jonathan Tushman
@jtushman

is it an anti-pattern to use both interfaces and unions together:

consider your docs ...

query {
  search(phrase: "Holmes") {
    ... on Actor {
      # maybe Katie Holmes?
      name
      age
    }
    ... on Movie {
      # for sure Sherlock Holmes!
      name
      rating
    }
  }
}

what if you wanted to

query {
  search(phrase: "Holmes") {
    name
    ... on Actor {
      # maybe Katie Holmes?
      age
    }
    ... on Movie {
      # for sure Sherlock Holmes!
      rating
    }
  }
}

have the common attributes be above the specific attributes

6 replies
tafelito
@tafelito
Hey guys!, trying to figure out what happens when you call multiple mutations from a single client in the same request, are they executed sequentially? Is there anyway to make all mutations to be part of a single transaction in typeorm?
8 replies
briandiephuis
@briandiephuis_gitlab
Hey all! We have some fields that have been marked deprecated for a while now. Is there a way to catch/subscribe/listen to the usage of deprecated fields so we can log these? This way we can make an informed decision whether or not to finally remove them from the api.
3 replies
Daniel de Witte
@Artimunor
Hi all
added an issue about a virus warning for a link in the wiki
2 replies
also have a question about an error i encounter, that i can solve but i am not sure that is the most optimal way
so when i select relations between objects that often works
however sometimes i get these errors, that it can not be null when i query it from graphiql
then the resolver could easily get it explicit
but i cant help to wonder if there is not a better way
{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Measurement.source.",
Measurement.source here is referenced like this in the entity:
  @Field(() => Source)
  @ManyToOne(() => Source)
  source: Source;
should that not be enough to load it on-demand if queried by graphql?
10 replies
wouldnt want to get it every time, even when the query is not specifically asking for it
icgarlin
@icgarlin
Screen Shot 2020-05-30 at 5.18.40 PM.png
Hi all! I'm having a lot of trouble with the following error
I have @babel/preset-typescript installed as a devDependency but it's still not working
2 replies