graphql#IntrospectionField TypeScript Examples

The following examples show how to use graphql#IntrospectionField. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: graphcms.ts    From next-right-now-admin with MIT License 6 votes vote down vote up
fieldAliasResolver = (
  field: IntrospectionField,
  fieldName: string,
  acc: FieldNode[],
  introspectionResults: IntrospectionResult,
): string => {
  if (isLocalisedField(fieldName)) {
    return getLocalisedFieldAlias(fieldName);
  }
  return fieldName;
}
Example #2
Source File: buildGqlQuery.ts    From ra-data-prisma with MIT License 6 votes vote down vote up
getArgType = (arg: IntrospectionField) => {
  const type = getFinalType(arg.type);
  const required = isRequired(arg.type);
  const list = isList(arg.type);

  if (list) {
    if (required) {
      return gqlTypes.listType(
        gqlTypes.nonNullType(gqlTypes.namedType(gqlTypes.name(type.name))),
      );
    }
    return gqlTypes.listType(gqlTypes.namedType(gqlTypes.name(type.name)));
  }

  if (required) {
    return gqlTypes.nonNullType(gqlTypes.namedType(gqlTypes.name(type.name)));
  }

  return gqlTypes.namedType(gqlTypes.name(type.name));
}
Example #3
Source File: buildGqlQuery.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
buildFields =
  (introspectionResults: IntrospectionResult) =>
  (
    fields: IntrospectionField[],
    maxNestingDepth = 1,
    depth = 0,
  ): FieldNode[] => {
    return fields.reduce((acc: FieldNode[], field) => {
      const type = getFinalType(field.type);

      if (type.name.startsWith("_")) {
        return acc;
      }
      // skip if the field has mandatory args
      if (field.args.some((arg) => arg.type.kind === "NON_NULL")) {
        return acc;
      }

      if (type.kind !== TypeKind.OBJECT) {
        return [...acc, gqlTypes.field(gqlTypes.name(field.name))];
      }

      const linkedResource = introspectionResults.resources.find(
        (r) => r.type.name === type.name,
      );
      if (linkedResource) {
        return [
          ...acc,
          gqlTypes.field(gqlTypes.name(field.name), {
            selectionSet: gqlTypes.selectionSet([
              gqlTypes.field(gqlTypes.name("id")),
            ]),
          }),
        ];
      }

      const linkedType = introspectionResults.types.find(
        (t) => t.name === type.name,
      );

      // linkedtypes  (= nested objects) are currently a bit problematic
      // it is handy to have them, but they be slow to fetch
      // we therefore limit the depth
      if (linkedType && depth < maxNestingDepth) {
        return [
          ...acc,
          gqlTypes.field(gqlTypes.name(field.name), {
            selectionSet: gqlTypes.selectionSet(
              buildFields(introspectionResults)(
                (linkedType as any).fields,
                maxNestingDepth,
                depth + 1,
              ),
            ),
          }),
        ];
      }

      return acc;
    }, [] as FieldNode[]);
  }
Example #4
Source File: introspection.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
makeIntrospectionField = (
  field: PartialField,
): IntrospectionField => ({
  args: [],
  isDeprecated: false,
  ...field,
})
Example #5
Source File: buildGqlQuery.test.ts    From ra-data-prisma with MIT License 4 votes vote down vote up
describe("buildGqlQuery", () => {
  let testIntrospectionNexus: IntrospectionResult;

  let testIntrospectionTypeGraphql: IntrospectionResult;
  let testIntrospectionWithPrefix: IntrospectionResult;
  let testUserResourceNexus: Resource;
  let testUserResourceTypeGraphql: Resource;
  beforeAll(async () => {
    testIntrospectionNexus = await getTestIntrospectionNexus();
    testIntrospectionTypeGraphql = await getTestIntrospectionTypeGraphql();

    testUserResourceNexus = testIntrospectionNexus.resources.find(
      (r) => r.type.kind === "OBJECT" && r.type.name === "User",
    );
    testUserResourceTypeGraphql = testIntrospectionTypeGraphql.resources.find(
      (r) => r.type.kind === "OBJECT" && r.type.name === "User",
    );
  });

  describe("getArgType", () => {
    it("returns the arg type", () => {
      expect(
        getArgType({
          type: { kind: TypeKind.SCALAR, name: "foo" },
        } as IntrospectionField),
      ).toEqualGraphql("foo");
    });

    it("returns the arg type for NON_NULL types", () => {
      expect(
        getArgType({
          type: {
            kind: TypeKind.NON_NULL,
            ofType: { name: "ID", kind: TypeKind.SCALAR },
          },
        } as IntrospectionField),
      ).toEqualGraphql("ID!");
    });

    it("returns the arg type for LIST types", () => {
      expect(
        getArgType({
          type: {
            kind: TypeKind.LIST,
            ofType: { name: "ID", kind: TypeKind.SCALAR },
          },
        } as IntrospectionField),
      ).toEqualGraphql("[ID]");
    });

    it("returns the arg type for LIST types of NON_NULL type", () => {
      expect(
        getArgType({
          type: {
            kind: TypeKind.LIST,
            ofType: {
              kind: TypeKind.NON_NULL,
              ofType: {
                kind: TypeKind.SCALAR,
                name: "ID",
              },
            },
          },
        } as IntrospectionField),
      ).toEqualGraphql("[ID!]");
    });
  });

  describe("buildArgs", () => {
    it("returns an empty array when query does not have any arguments", () => {
      expect(buildArgs({ args: [] } as Query)).toEqual([]);
    });

    it("returns an array of args correctly filtered when query has arguments", () => {
      expect(
        buildArgs({ args: [{ name: "foo" }, { name: "bar" }] } as Query, {
          foo: "foo_value",
        }),
      ).toEqualGraphql(["foo: $foo"]);
    });
  });

  describe("buildApolloArgs", () => {
    it("returns an empty array when query does not have any arguments", () => {
      expect(buildApolloArgs({ args: [] })).toEqualGraphql([]);
    });

    it("returns an array of args correctly filtered when query has arguments", () => {
      expect(
        buildApolloArgs(
          {
            args: [
              {
                name: "foo",
                type: {
                  kind: TypeKind.NON_NULL,
                  ofType: {
                    kind: TypeKind.SCALAR,
                    name: "Int",
                  },
                },
              },
              {
                name: "barId",
                type: { kind: TypeKind.SCALAR, name: "ID" },
              },
              {
                name: "barIds",
                type: {
                  kind: TypeKind.LIST,
                  ofType: {
                    kind: TypeKind.NON_NULL,
                    ofType: {
                      kind: TypeKind.SCALAR,
                      name: "ID",
                    },
                  },
                },
              },
              { name: "bar" },
            ],
          } as Query,
          { foo: "foo_value", barId: 100, barIds: [101, 102] },
        ),
      ).toEqualGraphql(["$foo: Int!", "$barId: ID", "$barIds: [ID!]"]);
    });
  });

  describe("buildFields", () => {
    it("returns an object with the fields to retrieve", () => {
      const introspectionResults: IntrospectionResult = makeIntrospectionResult(
        {
          resources: [{ type: { name: "resourceType", fields: [] } }],
          types: [
            {
              name: "linkedType",
              kind: "OBJECT",
              interfaces: [],
              fields: [
                {
                  name: "id",
                  type: { kind: TypeKind.SCALAR, name: "ID" },
                },
              ].map(makeIntrospectionField),
            },
          ],
        },
      );

      const fields: IntrospectionField[] = [
        {
          type: { kind: TypeKind.SCALAR, name: "ID" },
          name: "id",
        },
        {
          type: { kind: TypeKind.SCALAR, name: "_internalField" },
          name: "foo1",
        },
        {
          type: { kind: TypeKind.OBJECT, name: "linkedType" },
          name: "linked",
        },
        {
          type: { kind: TypeKind.OBJECT, name: "resourceType" },
          name: "resource",
        },
      ].map(makeIntrospectionField);

      expect(buildFields(introspectionResults)(fields)).toEqualGraphql([
        "id",
        `linked { id }`, // currently disabled
        `resource { id }`,
      ]);
    });
  });

  describe("buildGqlQuery", () => {
    const where = { firstName: "foo_value" };

    it("returns the correct query for GET_LIST", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          GET_LIST,
          { where },
          null,
        ),
      ).toEqualGraphql(
        gql`
          query users($where: UserWhereInput) {
            items: users(where: $where) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
            total: usersCount(where: $where)
          }
        `,
      );
    });

    it("returns the correct query for GET_LIST with typegraphql count query", () => {
      expect(
        buildGqlQuery(testIntrospectionTypeGraphql, {
          ...defaultOurOptions,
          queryDialect: "typegraphql",
        })(testUserResourceTypeGraphql, GET_LIST, { where }, null),
      ).toEqualGraphql(
        gql`
          query users($where: UserWhereInput) {
            items: users(where: $where) {
              id
              email
              firstName
              lastName
              gender
              yearOfBirth

              wantsNewsletter
              interests
              weddingDate
              _count {
                roles
                blogPosts
                comments
                companies
              }
              roles {
                id
              }
              userSocialMedia {
                id
                instagram
                twitter
                userId
              }

              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              address {
                street
                city
                countryCode
              }
            }
            total: aggregateUser(where: $where) {
              _count {
                _all
              }
            }
          }
        `,
      );
    });

    it("returns the correct query for GET_LIST when defining a fragment", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          GET_LIST,
          { where },
          gqlReal`
            fragment UserWithTwitter on User {
              id
              socialMedia {
                twitter
              }
            }
          `,
        ),
      ).toEqualGraphql(
        gql`
          query users($where: UserWhereInput) {
            items: users(where: $where) {
              id
              socialMedia {
                twitter
              }
            }
            total: usersCount(where: $where)
          }
        `,
      );
    });
    it("returns the correct query for GET_MANY", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          GET_MANY,
          { where },
          null,
        ),
      ).toEqualGraphql(
        gql`
          query users($where: UserWhereInput) {
            items: users(where: $where) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
            total: usersCount(where: $where)
          }
        `,
      );
    });
    it("returns the correct query for GET_MANY_REFERENCE", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          GET_MANY_REFERENCE,
          { where },
          null,
        ),
      ).toEqualGraphql(
        gql`
          query users($where: UserWhereInput) {
            items: users(where: $where) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
            total: usersCount(where: $where)
          }
        `,
      );
    });
    it("returns the correct query for GET_ONE", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          GET_ONE,

          { where },
          null,
        ),
      ).toEqualGraphql(
        gql`
          query user($where: UserWhereUniqueInput!) {
            data: user(where: $where) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
          }
        `,
      );
    });
    it("returns the correct query for UPDATE", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          UPDATE,
          { where, data: {} },
          null,
        ),
      ).toEqualGraphql(
        gql`
          mutation updateOneUser(
            $data: UserUpdateInput!
            $where: UserWhereUniqueInput!
          ) {
            data: updateOneUser(data: $data, where: $where) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
          }
        `,
      );
    });
    it("returns the correct query for CREATE", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          CREATE,
          { data: {} },
          null,
        ),
      ).toEqualGraphql(
        gql`
          mutation createOneUser($data: UserCreateInput!) {
            data: createOneUser(data: $data) {
              id
              email
              firstName
              lastName
              yearOfBirth
              roles {
                id
              }
              gender
              wantsNewsletter
              userSocialMedia {
                id
                instagram
                twitter
                user {
                  id
                }
              }
              blogPosts {
                id
              }
              comments {
                id
              }
              companies {
                id
              }
              interests
              weddingDate
              address {
                street
                city
                countryCode
              }
            }
          }
        `,
      );
    });
    it("returns the correct query for DELETE", () => {
      expect(
        buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
          testUserResourceNexus,
          DELETE,
          { where },
          null,
        ),
      ).toEqualGraphql(
        gql`
          mutation deleteOneUser($where: UserWhereUniqueInput!) {
            data: deleteOneUser(where: $where) {
              id
            }
          }
        `,
      );
    });

    describe("with prefixed introspections", () => {
      beforeAll(async () => {
        testIntrospectionNexus = await getTestIntrospectionNexus({
          aliasPrefix: "admin",
        });
        testUserResourceNexus = testIntrospectionNexus.resources.find(
          (r) => r.type.kind === "OBJECT" && r.type.name === "User",
        );
      });

      it("allows to prefix all queries with a prefix", () => {
        expect(
          buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
            testUserResourceNexus,
            GET_LIST,
            { where },
            null,
          ),
        ).toEqualGraphql(
          gql`
            query adminUsers($where: UserWhereInput) {
              items: adminUsers(where: $where) {
                id
                email
                firstName
                lastName
                yearOfBirth
                roles {
                  id
                }
                gender
                wantsNewsletter
                userSocialMedia {
                  id
                  instagram
                  twitter
                  user {
                    id
                  }
                }
                blogPosts {
                  id
                }
                comments {
                  id
                }
                companies {
                  id
                }
                interests
                weddingDate
                address {
                  street
                  city
                  countryCode
                }
              }
              total: adminUsersCount(where: $where)
            }
          `,
        );
      });
      it("allows to prefix all mutations with a prefix", () => {
        expect(
          buildGqlQuery(testIntrospectionNexus, defaultOurOptions)(
            testUserResourceNexus,
            DELETE,
            { where },
            null,
          ),
        ).toEqualGraphql(
          gql`
            mutation adminDeleteOneUser($where: UserWhereUniqueInput!) {
              data: adminDeleteOneUser(where: $where) {
                id
              }
            }
          `,
        );
      });
    });
  });
});