graphql-request#GraphQLClient TypeScript Examples

The following examples show how to use graphql-request#GraphQLClient. 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: index.ts    From platyplus with MIT License 6 votes vote down vote up
/**
 * * Simple graphql-request wrapper. Pre-configured Hasura parameters (endpoint and admin-secret)
 */
export class Client extends GraphQLClient {
  constructor(
    endpoint = DEFAULT_HASURA_ENDPOINT,
    secret = DEFAULT_ADMIN_SECRET
  ) {
    super(
      endpoint,
      secret
        ? {
            headers: {
              'x-hasura-admin-secret': secret
            }
          }
        : undefined
    )
  }
}
Example #2
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allUseCases), {
    where: {
      slug: { current: { eq: slug } },
    },
  });

  let useCase = data.allUseCase.find((p) => p.slug.current === slug);

  return {
    props: {
      ...useCase,
    },
    revalidate: 1,
  };
}
Example #3
Source File: graphQLClient.ts    From fishbowl with MIT License 6 votes vote down vote up
export function graphQLClient(
  credentials: { jwt?: string; adminSecret?: string } = {},
  hasuraEndpoint = process.env.HASURA_ENDPOINT || ""
) {
  const headers: Record<string, string> = {}
  if (credentials.jwt) {
    headers["Authorization"] = `Bearer ${credentials.jwt}`
  }
  if (credentials.adminSecret) {
    headers["x-hasura-admin-secret"] = credentials.adminSecret
  }

  const client = new GraphQLClient(hasuraEndpoint, {
    headers: {
      ...headers,
      "Content-Type": "application/json",
    },
  })
  return getSdk(client)
}
Example #4
Source File: base.ts    From backend with MIT License 6 votes vote down vote up
/* -------------- GraphQL Client Wrapper ------------------ */

// This wrapper provides assertions and logging around a GraphQLClient of the graphql-request package
function wrapClient(client: GraphQLClient) {
    async function request(query: string) {
        const name = query.match(/(mutation|query) [A-Za-z]+/)?.[0] ?? "(unnamed)";
        console.log(blue(`+ ${name}`));
        if (!silent) {
            console.log(`   request:`, query.trim());
        }
        const response = await client.request(query);
        if (!silent) {
            console.log(`   response:`, response);
        }
        return response;
    }

    async function requestShallFail(query: string): Promise<never> {
        const name = query.match(/(mutation|query) [A-Za-z]+/)?.[0] ?? "(unnamed)";
        console.log(blue(`+ ${name}`));

        if (!silent) {
            console.log(`  request (should fail):`, query.trim());
        }

        try {
            await client.request(query);
        } catch (error) {
            if (!silent) {
                console.log(`  successfully failed with ${error.message.split(":")[0]}`);
            }
            return;
        }

        throw new Error(`Request shall fail`);
    }

    return { request, requestShallFail };
}
Example #5
Source File: team.tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps() {
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  const data: any = await graphQLClient.request(print(allPages), {
    where: {
      slug: { current: { eq: "team" } },
    },
  });

  return {
    props: {
      ...data.allPage[0],
      preview: false,
    },
    revalidate: 1,
  };
}
Example #6
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;

  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allProducts), {
    where: {
      slug: { current: { eq: slug } },
    },
  });

  let product = data.allProduct.find((p) => p.slug.current === slug);

  return {
    props: {
      ...product,
    },
    revalidate: 1,
  };
}
Example #7
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getServerSideProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default",
    {
      headers: {
        authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
      },
    }
  );

  let data: any = await graphQLClient.request(print(allUseCases), {
    where: {
      _: { is_draft: true },
      slug: { current: { eq: slug } },
    },
  });

  // if in preview mode but no draft exists, then return published post
  if (!data.allUseCase.length) {
    data = await graphQLClient.request(print(allUseCases), {
      where: {
        _: { is_draft: false },
        slug: { current: { eq: slug } },
      },
    });
  }

  let useCase = data.allUseCase.find((p) => p.slug.current === slug);

  return {
    props: {
      ...useCase,
      noindex: true,
      preview: true,
    },
  };
}
Example #8
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getServerSideProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default",
    {
      headers: {
        authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
      },
    }
  );

  let data: any = await graphQLClient.request(print(allProducts), {
    where: {
      _: { is_draft: true },
      slug: { current: { eq: slug } },
    },
  });

  // if in preview mode but no draft exists, then return published post
  if (!data.allProduct.length) {
    data = await graphQLClient.request(print(allProducts), {
      where: {
        _: { is_draft: false },
        slug: { current: { eq: slug } },
      },
    });
  }

  let product = data.allProduct.find((p) => p.slug.current === slug);

  return {
    props: {
      ...product,
      noindex: true,
      preview: true,
    },
  };
}
Example #9
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getServerSideProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default",
    {
      headers: {
        authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
      },
    }
  );

  let data: any = await graphQLClient.request(print(allPosts), {
    where: {
      _: { is_draft: true },
      slug: { current: { eq: slug } },
    },
  });

  // if in preview mode but no draft exists, then return published post
  if (!data.allPost.length) {
    data = await graphQLClient.request(print(allPosts), {
      where: {
        _: { is_draft: false },
        slug: { current: { eq: slug } },
      },
    });
  }

  let post = data.allPost.find((p) => p.slug.current === slug);

  return {
    props: {
      ...post,
      noindex: true,
      preview: true,
    },
  };
}
Example #10
Source File: __helpers.ts    From tutorial with MIT License 6 votes vote down vote up
function graphqlTestContext() {
  let serverInstance: ServerInfo | null = null

  return {
    async before() {
      const port = await getPort({ port: makeRange(4000, 6000) })

      serverInstance = await server.listen({ port })
      serverInstance.server.on('close', async () => {
        await db.$disconnect()
      })

      return new GraphQLClient(`http://localhost:${port}`)
    },
    async after() {
      serverInstance?.server.close()
    },
  }
}
Example #11
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allPages), {
    where: {
      slug: { current: { eq: slug } },
    },
  });

  let page = data.allPage.find((p) => p.slug.current === slug);

  return {
    props: {
      ...page,
    },
    revalidate: 1,
  };
}
Example #12
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticPaths() {
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );
  const { allPost } = await graphQLClient.request(print(allPosts), {
    where: {},
  });

  let paths = [];
  for (const post of allPost) {
    paths.push({ params: { slug: post.slug.current } });
  }
  return {
    fallback: true,
    paths,
  };
}
Example #13
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allPosts), {
    where: {},
  });

  let post = data.allPost.find((p) => p.slug.current === slug);

  // TODO: fetch related posts from sanity
  const furtherReading = data.allPost
    .filter((p) => p.slug.current !== slug)
    .sort(() => 0.5 - Math.random())
    .slice(0, 2);

  return {
    props: {
      ...post,
      furtherReading,
    },
    revalidate: 1,
  };
}
Example #14
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getServerSideProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default",
    {
      headers: {
        authorization: `Bearer ${process.env.SANITY_API_TOKEN}`,
      },
    }
  );

  let data: any = await graphQLClient.request(print(allPages), {
    where: {
      _: { is_draft: true },
      slug: { current: { eq: slug } },
    },
  });

  // if in preview mode but no draft exists, then return published post
  if (!data.allPage.length) {
    data = await graphQLClient.request(print(allPages), {
      where: {
        _: { is_draft: false },
        slug: { current: { eq: slug } },
      },
    });
  }

  let page = data.allPage.find((p) => p.slug.current === slug);

  return {
    props: {
      ...page,
      noindex: true,
      preview: true,
    },
  };
}
Example #15
Source File: github.ts    From merged-pr-stat with MIT License 5 votes vote down vote up
graphQLClient = new GraphQLClient(GITHUB_GRAPHQL_ENDPOINT, {
  headers: {
    authorization: `Bearer ${GITHUB_TOKEN}`,
  },
  timeout: 3600_000,
})
Example #16
Source File: provider.ts    From fuels-ts with Apache License 2.0 5 votes vote down vote up
constructor(
    /** GraphQL endpoint of the Fuel node */
    public url: string
  ) {
    const gqlClient = new GraphQLClient(url);
    this.operations = getOperationsSdk(gqlClient);
  }
Example #17
Source File: graphQLApi.ts    From github-deploy-center with MIT License 5 votes vote down vote up
graphQLClient = new GraphQLClient(githubGraphQLApiUrl)
Example #18
Source File: graphql.ts    From homebase-app with MIT License 5 votes vote down vote up
client = new GraphQLClient(BASE_URL, {
  headers: {
    "content-type": "application/json",
    "x-hasura-admin-secret": HASURA_ADMIN_SECRET,
  },
})
Example #19
Source File: base.ts    From backend with MIT License 5 votes vote down vote up
adminClient = wrapClient(new GraphQLClient(URL, {
    headers: {
        authorization: `Basic ${Buffer.from("admin:" + ADMIN_TOKEN).toString("base64")}`
    }
}))
Example #20
Source File: base.ts    From backend with MIT License 5 votes vote down vote up
defaultClient = wrapClient(new GraphQLClient(URL))
Example #21
Source File: base.ts    From backend with MIT License 5 votes vote down vote up
export function createUserClient() {
    return wrapClient(new GraphQLClient(URL, {
        headers: {
            authorization: `Bearer ${randomBytes(36).toString("base64")}`
        }
    }));
}
Example #22
Source File: licenseCheck.ts    From projects-bot with MIT License 5 votes vote down vote up
ghClient = new GraphQLClient('https://api.github.com/graphql')
Example #23
Source File: graphql.client.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
graphQLClient = new GraphQLClient(url)
Example #24
Source File: index.ts    From atlas with GNU General Public License v3.0 5 votes vote down vote up
client = new GraphQLClient(GRAPHQL_URL)
Example #25
Source File: resolvers.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('GrahpQL Resolvers', () => {
  beforeAll(async (done) => {
    const query = `
      mutation {
        loginAdmin(
          email: "${email}",
          password: "${password}"
        ) {
          token
        }
      }`;

    const response = await request(url, query);

    token = response.loginAdmin.token;

    client = new GraphQLClient(url, { headers: { Authorization: `JWT ${token}` } });

    done();
  });

  describe('Create', () => {
    it('should allow a localized post to be created', async () => {
      const title = 'gql create';
      const description = 'description';

      // language=graphQL
      const query = `mutation {
          createLocalizedPost(data: {title: "${title}", description: "${description}", priority: 10}) {
          id
          title
          description
          priority
          createdAt
          updatedAt
        }
      }`;

      const response = await client.request(query);

      const data = response.createLocalizedPost;

      expect(data.title).toBe(title);
      expect(data.id).toStrictEqual(expect.any(String));
      // const timestampRegex = /^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/;
      // expect(data.createdAt).toStrictEqual(expect.stringMatching(timestampRegex));
      // expect(data.updatedAt).toStrictEqual(expect.stringMatching(timestampRegex));
      expect(data.createdAt).toStrictEqual(expect.any(String));
      expect(data.updatedAt).toStrictEqual(expect.any(String));
    });
  });

  describe('Read', () => {
    it('should be able to read localized post', async () => {
      const title = 'gql read 1';
      const description = 'description';

      // language=graphQL
      const query = `mutation {
            createLocalizedPost(data: {title: "${title}", description: "${description}", priority: 10}) {
            id
            title
            description
            priority
            createdAt
            updatedAt
          }
        }`;

      const response = await client.request(query);

      const { id } = response.createLocalizedPost;
      // language=graphQL
      const readQuery = `query {
        LocalizedPost(id: "${id}") {
          id
        }
      }`;
      const readResponse = await client.request(readQuery);
      const retrievedId = readResponse.LocalizedPost.id;

      expect(retrievedId).toStrictEqual(id);
    });

    it('should query exists - true', async () => {
      const title = 'gql read 2';
      const description = 'description';
      const summary = 'summary';

      // language=graphQL
      const query = `mutation {
            createLocalizedPost(data: {title: "${title}", description: "${description}", summary: "${summary}", priority: 10}) {
            id
            title
            description
            priority
            createdAt
            updatedAt
          }
        }`;

      const response = await client.request(query);

      const { id } = response.createLocalizedPost;
      // language=graphQL
      const readQuery = `query {
  LocalizedPosts(where: { summary: { exists: true }}) {
    docs {
      id
      description
      summary
    }
  }
}`;
      const readResponse = await client.request(readQuery);
      const retrievedId = readResponse.LocalizedPosts.docs[0].id;

      expect(readResponse.LocalizedPosts.docs).toHaveLength(1);
      expect(retrievedId).toStrictEqual(id);
    });

    it('should query exists - false', async () => {
      const title = 'gql read 3';
      const description = 'description';

      // language=graphQL
      const query = `mutation {
            createLocalizedPost(data: {title: "${title}", description: "${description}", priority: 10}) {
            id
            title
            description
            priority
            createdAt
            updatedAt
          }
        }`;

      const response = await client.request(query);

      const { id } = response.createLocalizedPost;
      // language=graphQL
      const readQuery = `query {
  LocalizedPosts(where: { summary: { exists: false }}) {
    docs {
      id
      summary
    }
  }
}`;
      const readResponse = await client.request(readQuery);
      const retrievedDoc = readResponse.LocalizedPosts.docs[0];

      expect(readResponse.LocalizedPosts.docs.length).toBeGreaterThan(0);
      expect(retrievedDoc.id).toStrictEqual(id);
      expect(retrievedDoc.summary).toBeNull();
    });
  });

  describe('Update', () => {
    it('should allow updating an existing post', async () => {
      const title = 'gql update';
      const description = 'description';

      // language=graphQL
      const query = `mutation {
          createLocalizedPost(data: { title: "${title}", description: "${description}", priority: 10}) {
          id
          title
          description
          priority
        }
      }`;

      const createResponse = await client.request(query);

      const createData = createResponse.createLocalizedPost;
      const { id } = createData;
      const updatedDesc = 'updated description';

      // language=graphQL
      const update = `
      mutation {
        updateLocalizedPost(id: "${id}" data: {description: "${updatedDesc}"}) {
        description
      }
      }`;

      const response = await client.request(update);
      const data = response.updateLocalizedPost;

      expect(data.description).toBe(updatedDesc);
    });
  });

  describe('Delete', () => {
    it('should be able to delete a localized post', async () => {
      const title = 'gql delete';
      const description = 'description';

      // language=graphQL
      const query = `mutation {
            createLocalizedPost(data: {title: "${title}", description: "${description}", priority: 10}) {
            id
            title
            description
            priority
            createdAt
            updatedAt
          }
        }`;

      const response = await client.request(query);

      const { id } = response.createLocalizedPost;
      // language=graphQL
      const deleteMutation = `mutation {
        deleteLocalizedPost(id: "${id}") {
          id
        }
      }`;
      const deleteResponse = await client.request(deleteMutation);
      const deletedId = deleteResponse.deleteLocalizedPost.id;

      expect(deletedId).toStrictEqual(id);
    });
  });

  describe('Error Handler', () => {
    it('should return have an array of errors when making a bad request', async () => {
      let error;

      // language=graphQL
      const query = `query {
        LocalizedPosts(where: { summary: { exists: true }}) {
          docs {
            badFieldName
          }
        }
      }`;
      await client.request(query).catch((err) => {
        error = err;
      });
      expect(Array.isArray(error.response.errors)).toBe(true);
      expect(typeof error.response.errors[0].message).toBe('string');
    });

    it('should return have an array of errors when failing to pass validation', async () => {
      let error;
      // language=graphQL
      const query = `mutation {
          createLocalizedPost(data: {priority: 10}) {
          id
          priority
          createdAt
          updatedAt
        }
      }`;

      await client.request(query).catch((err) => {
        error = err;
      });
      expect(Array.isArray(error.response.errors)).toBe(true);
      expect(typeof error.response.errors[0].message).toBe('string');
    });
  });

  describe('Custom ID', () => {
    it('should create', async () => {
      const id = 10;
      const query = `mutation {
        createCustomID(data: {
          id: ${id},
          name: "custom"
        }) {
          id,
          name
        }
      }`;
      const response = await client.request(query);
      const data = response.createCustomID;
      expect(data.id).toStrictEqual(id);
    });

    it('should update', async () => {
      const id = 11;
      const name = 'custom name';

      const query = `
      mutation {
        createCustomID(data: {
          id: ${id},
          name: "${name}"
          }) {
          id
          name
        }
      }`;

      await client.request(query);
      const updatedName = 'updated name';

      const update = `
        mutation {
          updateCustomID(id: ${id} data: {name: "${updatedName}"}) {
          name
        }
      }`;

      const response = await client.request(update);
      const data = response.updateCustomID;

      expect(data.name).toStrictEqual(updatedName);
      expect(data.name).not.toStrictEqual(name);
    });

    it('should query on id', async () => {
      const id = 15;
      const name = 'custom name';

      const create = `mutation {
          createCustomID(data: {
          id: ${id},
          name: "${name}"
          }) {
          id
          name
        }
      }`;

      await client.request(create);

      const query = `
      query {
        CustomIDs(where: { id: { equals: ${id} } }) {
          docs {
            id
            name
          }
        }
      }`;
      const response = await client.request(query);
      const [doc] = response.CustomIDs.docs;
      expect(doc.id).toStrictEqual(id);
      expect(doc.name).toStrictEqual(name);
    });

    it('should delete', async () => {
      const id = 12;
      const query = `mutation {
          createCustomID(data: {
          id: ${id},
          name: "delete me"
          }) {
          id
          name
        }
      }`;

      await client.request(query);

      const deleteMutation = `mutation {
        deleteCustomID(id: ${id}) {
          id
        }
      }`;
      const deleteResponse = await client.request(deleteMutation);
      const deletedId = deleteResponse.deleteCustomID.id;

      expect(deletedId).toStrictEqual(id);
    });

    it('should allow relationships', async () => {
      const id = 13;
      const query = `mutation {
          createCustomID(data: {
            id: ${id},
            name: "relate me"
          }) {
            id
            name
        }
      }`;

      await client.request(query);
      const relation = `mutation {
        createRelationshipA(data: {
          customID: [ ${id} ]
        }) {
          customID {
            id
          }
        }
      }`;
      const relationResponse = await client.request(relation);
      const { customID } = relationResponse.createRelationshipA;

      expect(customID).toHaveLength(1);
      expect(customID).toHaveLength(1);
    });
  });
});
Example #26
Source File: pointField.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('GeoJSON', () => {
  beforeAll(async (done) => {
    const response = await fetch(`${serverURL}/api/admins/login`, {
      body: JSON.stringify({
        email,
        password,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'post',
    });

    const data = await response.json();

    ({ token } = data);
    headers = {
      Authorization: `JWT ${token}`,
      'Content-Type': 'application/json',
    };

    done();
  });

  describe('Point Field - REST', () => {
    let location = [10, 20];
    const localizedPoint = [30, 40];
    const group = { point: [15, 25] };
    let doc;

    beforeAll(async (done) => {
      const create = await fetch(`${serverURL}/api/geolocation`, {
        body: JSON.stringify({ location, localizedPoint, group }),
        headers,
        method: 'post',
      });
      ({ doc } = await create.json());

      done();
    });

    it('should create and read collections with points', async () => {
      expect(doc.id).toBeDefined();
      expect(doc.location).toStrictEqual(location);
      expect(doc.localizedPoint).toStrictEqual(localizedPoint);
    });

    it('should query where near point', async () => {
      const [lng, lat] = location;
      const hitResponse = await fetch(`${serverURL}/api/geolocation?where[location][near]=${lng + 0.01},${lat + 0.01},10000`, {
        headers,
        method: 'get',
      });
      const hitData = await hitResponse.json();
      const hitDocs = hitData.docs;

      const missResponse = await fetch(`${serverURL}/api/geolocation?where[location][near]=-${lng},-${lat},5000`, {
        headers,
        method: 'get',
      });
      const missData = await missResponse.json();
      const missDocs = missData.docs;

      expect(hitDocs).toHaveLength(1);
      expect(missDocs).toHaveLength(0);
    });

    it('should query where near localized point', async () => {
      const [lng, lat] = localizedPoint;
      const hitResponse = await fetch(`${serverURL}/api/geolocation?where[localizedPoint][near]=${lng + 0.01},${lat + 0.01},10000`, {
        headers,
        method: 'get',
      });
      const hitData = await hitResponse.json();
      const hitDocs = hitData.docs;

      const missResponse = await fetch(`${serverURL}/api/geolocation?where[localizedPoint][near]=-${lng},-${lat},5000`, {
        headers,
        method: 'get',
      });
      const missData = await missResponse.json();
      const missDocs = missData.docs;

      expect(hitDocs).toHaveLength(1);
      expect(missDocs).toHaveLength(0);
    });

    it('should query near a nested point', async () => {
      const [x, y] = group.point;
      const hitResponse = await fetch(`${serverURL}/api/geolocation?where[group.point][near]=${x + 0.01},${y + 0.01},10000`, {
        headers,
        method: 'get',
      });
      const hitData = await hitResponse.json();
      const hitDocs = hitData.docs;

      const missResponse = await fetch(`${serverURL}/api/geolocation?where[group.point][near]=-${x},-${y},5000`, {
        headers,
        method: 'get',
      });
      const missData = await missResponse.json();
      const missDocs = missData.docs;

      expect(hitDocs).toHaveLength(1);
      expect(missDocs).toHaveLength(0);
    });

    it('should save with non-required point', async () => {
      location = undefined;

      const create = await fetch(`${serverURL}/api/geolocation`, {
        body: JSON.stringify({ location }),
        headers,
        method: 'post',
      });

      const { doc } = await create.json();

      expect(doc.id).toBeDefined();
      expect(doc.location).toStrictEqual(location);
    });
  });


  describe('Point Field - GraphQL', () => {
    const url = `${serverURL}${routes.api}${routes.graphQL}`;
    let client = null;
    const location = [50, 60];
    const localizedPoint = [70, 80];
    const group = { point: [50.5, 60.5] };
    let doc;

    beforeAll(async (done) => {
      client = new GraphQLClient(url, { headers: { Authorization: `JWT ${token}` } });

      // language=graphQL
      const query = `mutation {
        createGeolocation (
          data: {
            location: [${location[0]}, ${location[1]}],
            localizedPoint: [${localizedPoint[0]}, ${localizedPoint[1]}],
            group: {
              point: [${group.point[0]}, ${group.point[1]}]
            }
          }
        ) {
          id
          location
          localizedPoint
        }
      }`;

      const response = await client.request(query);

      const { id } = response.createGeolocation;
      // language=graphQL
      const readQuery = `query {
        Geolocation(id: "${id}") {
          id
          location
          localizedPoint
        }
      }`;
      const readResponse = await client.request(readQuery);
      doc = readResponse.Geolocation;
      done();
    });

    it('should create and read collections with points', async () => {
      expect(doc.id).toBeDefined();
      expect(doc.location).toStrictEqual(location);
      expect(doc.localizedPoint).toStrictEqual(localizedPoint);
    });

    it('should query where near point', async () => {
      const [lng, lat] = location;
      // language=graphQL
      const hitQuery = `query getGeos {
        Geolocations(where: { location: { near: [${lng + 0.01},${lat + 0.01},10000]}}) {
          docs {
            id
            location
            localizedPoint
          }
        }
      }`;
      const hitResponse = await client.request(hitQuery);
      const hitDocs = hitResponse.Geolocations.docs;

      const missQuery = `query getGeos {
        Geolocations(where: { location: { near: [${-lng},${-lat},10000]}}) {
          docs {
            id
            location
            localizedPoint
          }
        }
      }`;
      const missResponse = await client.request(missQuery);
      const missDocs = missResponse.Geolocations.docs;

      expect(hitDocs).toHaveLength(1);
      expect(missDocs).toHaveLength(0);
    });

    it('should query where near a point in a group', async () => {
      const [x, y] = group.point;
      // language=graphQL
      const hitQuery = `query getGeos {
        Geolocations(where: { group__point: { near: [${x + 0.01},${y + 0.01},10000]}}) {
          docs {
            id
            group {
              point
            }
          }
        }
      }`;
      const hitResponse = await client.request(hitQuery);
      const hitDocs = hitResponse.Geolocations.docs;

      const missQuery = `query getGeos {
        Geolocations(where: { group__point: { near: [${-x},${-y},10000]}}) {
          docs {
            id
            group {
              point
            }
          }
        }
      }`;
      const missResponse = await client.request(missQuery);
      const missDocs = missResponse.Geolocations.docs;

      expect(hitDocs).toHaveLength(1);
      expect(missDocs).toHaveLength(0);
    });
  });
});
Example #27
Source File: uploads.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('Collections - Uploads', () => {
  beforeAll(async (done) => {
    const response = await fetch(`${api}/admins/login`, {
      body: JSON.stringify({
        email,
        password,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'post',
    });

    const data = await response.json();

    ({ token } = data);
    headers = {
      Authorization: `JWT ${token}`,
    };

    done();
  });

  describe('REST', () => {
    const mediaDir = path.join(__dirname, '../../../demo', 'media');
    beforeAll(async () => {
      // Clear demo/media directory
      const mediaDirExists = await fileExists(mediaDir);
      if (!mediaDirExists) return;
      fs.readdir(mediaDir, (err, files) => {
        if (err) throw err;

        // eslint-disable-next-line no-restricted-syntax
        for (const file of files) {
          fs.unlink(path.join(mediaDir, file), (unlinkErr) => {
            if (unlinkErr) throw unlinkErr;
          });
        }
      });
    });

    describe('create', () => {
      it('creates', async () => {
        const formData = new FormData();
        formData.append(
          'file',
          fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/image.png')),
        );
        formData.append('alt', 'test media');
        formData.append('locale', 'en');
        const response = await fetch(`${api}/media`, {
          body: formData as unknown as BodyInit,
          headers,
          method: 'post',
        });

        const data = await response.json();

        expect(response.status).toBe(201);

        // Check for files
        expect(await fileExists(path.join(mediaDir, 'image.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'image-16x16.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'image-320x240.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'image-640x480.png'))).toBe(true);

        // Check api response
        expect(data).toMatchObject({
          doc: {
            alt: 'test media',
            filename: 'image.png',
            mimeType: 'image/png',
            sizes: {
              icon: {
                filename: 'image-16x16.png',
                width: 16,
                height: 16,
              },
              mobile: {
                filename: 'image-320x240.png',
                width: 320,
                height: 240,
              },
              tablet: {
                filename: 'image-640x480.png',
                width: 640,
                height: 480,
              },
            },

            // We have a hook to check if upload sizes
            // are properly bound to the Payload `req`.
            // This field should be automatically set
            // if they are found.
            foundUploadSizes: true,
          },
        });
      });

      it('creates media without storing a file', async () => {
        const formData = new FormData();
        formData.append(
          'file',
          fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/image.png')),
        );
        formData.append('alt', 'test media');
        formData.append('locale', 'en');

        const response = await fetch(`${api}/unstored-media`, {
          body: formData as unknown as BodyInit,
          headers,
          method: 'post',
        });

        const data = await response.json();

        expect(response.status).toBe(201);

        // Check for files
        expect(await !fileExists(path.join(mediaDir, 'image.png'))).toBe(false);
        expect(await !fileExists(path.join(mediaDir, 'image-640x480.png'))).toBe(false);

        // Check api response
        expect(data).toMatchObject({
          doc: {
            alt: 'test media',
            filename: 'image.png',
            mimeType: 'image/png',
            sizes: {
              tablet: {
                filename: 'image-640x480.png',
                width: 640,
                height: 480,
              },
            },
          },
        });
      });

      it('creates with same name', async () => {
        const formData = new FormData();
        formData.append(
          'file',
          fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/samename.png')),
        );
        formData.append('alt', 'test media');
        formData.append('locale', 'en');

        const firstResponse = await fetch(`${api}/media`, {
          body: formData as unknown as BodyInit,
          headers,
          method: 'post',
        });

        expect(firstResponse.status).toBe(201);

        const sameForm = new FormData();
        sameForm.append(
          'file',
          fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/samename.png')),
        );
        sameForm.append('alt', 'test media');
        sameForm.append('locale', 'en');

        const response = await fetch(`${api}/media`, {
          body: sameForm as unknown as BodyInit,
          headers,
          method: 'post',
        });

        expect(response.status).toBe(201);
        const data = await response.json();

        // Check for files
        expect(await fileExists(path.join(mediaDir, 'samename-1.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'samename-1-16x16.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'samename-1-320x240.png'))).toBe(true);
        expect(await fileExists(path.join(mediaDir, 'samename-1-640x480.png'))).toBe(true);

        expect(data).toMatchObject({
          doc: {
            alt: 'test media',
            filename: 'samename-1.png',
            mimeType: 'image/png',
            sizes: {
              icon: {
                filename: 'samename-1-16x16.png',
                width: 16,
                height: 16,
              },
              mobile: {
                filename: 'samename-1-320x240.png',
                width: 320,
                height: 240,
              },
              tablet: {
                filename: 'samename-1-640x480.png',
                width: 640,
                height: 480,
              },
            },
          },
        });
      });
    });

    it('update', async () => {
      const formData = new FormData();
      formData.append(
        'file',
        fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/update.png')),
      );
      formData.append('alt', 'test media');
      formData.append('locale', 'en');

      const response = await fetch(`${api}/media`, {
        body: formData as unknown as BodyInit,
        headers,
        method: 'post',
      });

      const data = await response.json();

      expect(response.status).toBe(201);

      const updateFormData = new FormData();
      const newAlt = 'my new alt';

      updateFormData.append('filename', data.doc.filename);
      updateFormData.append('alt', newAlt);
      const updateResponse = await fetch(`${api}/media/${data.doc.id}`, {
        body: updateFormData as unknown as BodyInit,
        headers,
        method: 'put',
      });

      expect(updateResponse.status).toBe(200);

      const updateResponseData = await updateResponse.json();

      // Check that files weren't affected
      expect(await fileExists(path.join(mediaDir, 'update.png'))).toBe(true);
      expect(await fileExists(path.join(mediaDir, 'update-16x16.png'))).toBe(true);
      expect(await fileExists(path.join(mediaDir, 'update-320x240.png'))).toBe(true);
      expect(await fileExists(path.join(mediaDir, 'update-640x480.png'))).toBe(true);

      // Check api response
      expect(updateResponseData).toMatchObject({
        doc: {
          alt: newAlt,
          filename: 'update.png',
          mimeType: 'image/png',
          sizes: {
            icon: {
              filename: 'update-16x16.png',
              width: 16,
              height: 16,
            },
            mobile: {
              filename: 'update-320x240.png',
              width: 320,
              height: 240,
            },
            tablet: {
              filename: 'update-640x480.png',
              width: 640,
              height: 480,
            },
            maintainedAspectRatio: {},
          },
        },
      });
    });

    it('delete', async () => {
      const formData = new FormData();
      formData.append(
        'file',
        fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/delete.png')),
      );
      formData.append('alt', 'test media');
      formData.append('locale', 'en');

      const createResponse = await fetch(`${api}/media`, {
        body: formData as unknown as BodyInit,
        headers,
        method: 'post',
      });

      const createData = await createResponse.json();
      expect(createResponse.status).toBe(201);
      const docId = createData.doc.id;

      const response = await fetch(`${api}/media/${docId}`, {
        headers,
        method: 'delete',
      });

      const data = await response.json();
      expect(response.status).toBe(200);
      expect(data.id).toBe(docId);

      const imageExists = await fileExists(path.join(mediaDir, 'delete.png'));
      expect(imageExists).toBe(false);
    });
  });

  describe('GraphQL', () => {
    // graphql cannot submit formData to create files, we only need to test getting relationship data on upload fields
    let media;
    let image;
    const alt = 'alt text';
    beforeAll(async (done) => {
      client = new GraphQLClient(`${api}${config.routes.graphQL}`, {
        headers: { Authorization: `JWT ${token}` },
      });

      // create media using REST
      const formData = new FormData();
      formData.append(
        'file',
        fs.createReadStream(path.join(__dirname, '../../..', 'tests/api/assets/image.png')),
      );
      formData.append('alt', alt);
      formData.append('locale', 'en');
      const mediaResponse = await fetch(`${api}/media`, {
        body: formData as unknown as BodyInit,
        headers,
        method: 'post',
      });
      const mediaData = await mediaResponse.json();
      media = mediaData.doc;

      // create image that relates to media
      headers['Content-Type'] = 'application/json';
      const imageResponse = await fetch(`${api}/images`, {
        body: JSON.stringify({
          upload: media.id,
        }),
        headers,
        method: 'post',
      });
      const data = await imageResponse.json();
      image = data.doc;

      done();
    });

    it('should query uploads relationship fields', async () => {
      // language=graphQL
      const query = `query {
          Image(id: "${image.id}") {
            id
            upload {
              alt
            }
          }
        }`;

      const response = await client.request(query);
      expect(response.Image.upload.alt).toStrictEqual(alt);
    });
  });
});
Example #28
Source File: resolvers.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('GrahpQL Preferences', () => {
  beforeAll(async (done) => {
    const query = `
      mutation {
        loginAdmin(
          email: "${email}",
          password: "${password}"
        ) {
          token
        }
      }`;

    const response = await request(url, query);

    token = response.loginAdmin.token;

    client = new GraphQLClient(url, { headers: { Authorization: `JWT ${token}` } });

    done();
  });

  describe('Update', () => {
    it('should allow a preference to be saved', async () => {
      const key = 'preference-key';
      const value = 'preference-value';

      // language=graphQL
      const query = `mutation {
          updatePreference(key: "${key}", value: "${value}") {
          key
          value
        }
      }`;

      const response = await client.request(query);

      const data = response.updatePreference;

      expect(data.key).toBe(key);
      expect(data.value).toBe(value);
    });
  });

  describe('Read', () => {
    it('should be able to read user preference', async () => {
      const key = 'preference-key';
      const value = 'preference-value';

      // language=graphQL
      const query = `mutation {
          updatePreference(key: "${key}", value: "${value}") {
          key
          value
        }
      }`;

      const response = await client.request(query);

      const { key: responseKey, value: responseValue } = response.updatePreference;
      // language=graphQL
      const readQuery = `query {
        Preference(key: "${responseKey}") {
          key
          value
        }
      }`;
      const readResponse = await client.request(readQuery);

      expect(responseKey).toStrictEqual(key);
      expect(readResponse.Preference.key).toStrictEqual(key);
      expect(responseValue).toStrictEqual(value);
      expect(readResponse.Preference.value).toStrictEqual(value);
    });
  });

  describe('Delete', () => {
    it('should be able to delete a preference', async () => {
      const key = 'gql-delete';
      const value = 'description';

      // language=graphQL
      const query = `mutation {
            updatePreference(key: "${key}" value: "${value}") {
            key
            value
          }
        }`;

      const response = await client.request(query);

      const { key: responseKey } = response.updatePreference;
      // language=graphQL
      const deleteMutation = `mutation {
        deletePreference(key: "${key}") {
          key
          value
        }
      }`;
      const deleteResponse = await client.request(deleteMutation);
      const deleteKey = deleteResponse.deletePreference.key;

      expect(responseKey).toStrictEqual(key);
      expect(deleteKey).toStrictEqual(key);
    });
  });

  it('should return null when query key is not found', async () => {
    const key = 'bad-key';
    const readQuery = `query {
        Preference(key: "${key}") {
          key
          value
        }
      }`;
    const response = await client.request(readQuery);

    expect(response.Preference).toBeNull();
  });
});
Example #29
Source File: collections-graphql.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('Collections GrahpQL Version Resolvers', () => {
  const title = 'autosave title';

  beforeAll(async (done) => {
    const login = `
      mutation {
        loginAdmin(
          email: "${email}",
          password: "${password}"
        ) {
          token
        }
      }`;

    const response = await request(url, login);

    token = response.loginAdmin.token;

    client = new GraphQLClient(url, { headers: { Authorization: `JWT ${token}` } });

    done();
  });

  describe('Create', () => {
    it('should allow a new autosavePost to be created with draft status', async () => {
      const description = 'autosave description';

      const query = `mutation {
          createAutosavePost(data: {title: "${title}", description: "${description}"}) {
          id
          title
          description
          createdAt
          updatedAt
          _status
        }
      }`;

      const response = await client.request(query);

      const data = response.createAutosavePost;
      postID = data.id;

      expect(data._status).toStrictEqual('draft');
    });
  });

  describe('Read', () => {
    const updatedTitle = 'updated title';

    beforeAll(async (done) => {
      // modify the post to create a new version
      // language=graphQL
      const update = `mutation {
        updateAutosavePost(id: "${postID}", data: {title: "${updatedTitle}"}) {
          title
        }
      }`;
      await client.request(update);

      // language=graphQL
      const query = `query {
          versionsAutosavePosts(where: { parent: { equals: "${postID}" } }) {
          docs {
            id
          }
        }
      }`;

      const response = await client.request(query);

      versionID = response.versionsAutosavePosts.docs[0].id;
      done();
    });

    it('should allow read of versions by version id', async () => {
      const query = `query {
        versionAutosavePost(id: "${versionID}") {
          id
          parent {
            id
          }
          version {
            title
          }
        }
      }`;

      const response = await client.request(query);

      const data = response.versionAutosavePost;
      versionID = data.id;

      expect(data.id).toBeDefined();
      expect(data.parent.id).toStrictEqual(postID);
      expect(data.version.title).toStrictEqual(title);
    });

    it('should allow read of versions by querying version content', async () => {
      // language=graphQL
      const query = `query {
          versionsAutosavePosts(where: { version__title: {equals: "${title}" } }) {
          docs {
            id
            parent {
            id
          }
            version {
              title
            }
          }
        }
      }`;

      const response = await client.request(query);

      const data = response.versionsAutosavePosts;
      const doc = data.docs[0];
      versionID = doc.id;

      expect(doc.id).toBeDefined();
      expect(doc.parent.id).toStrictEqual(postID);
      expect(doc.version.title).toStrictEqual(title);
    });
  });

  describe('Restore', () => {
    it('should allow a version to be restored', async () => {
      // update a versionsPost
      const restore = `mutation {
        restoreVersionAutosavePost(id: "${versionID}") {
          title
        }
      }`;

      await client.request(restore);

      const query = `query {
        AutosavePost(id: "${postID}") {
          title
        }
      }`;

      const response = await client.request(query);
      const data = response.AutosavePost;
      expect(data.title).toStrictEqual(title);
    });
  });
});