@apollo/client#createHttpLink TypeScript Examples

The following examples show how to use @apollo/client#createHttpLink. 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: client.ts    From Frontend with MIT License 6 votes vote down vote up
createClient = () => {
  const uri = process.env.GATSBY_GRAPHQL_ENDPOINT;

  const httpLink = createHttpLink({
    uri,
    fetch
  });

  const authToken = hasWindow ? localStorage.getItem('token') : '';

  const authLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        authorization: authToken ? `Bearer ${authToken}` : ''
      }
    });

    return forward(operation);
  });

  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache({
      dataIdFromObject: (object) => {
        // eslint-disable-next-line no-underscore-dangle
        switch (object.__typename) {
          case 'Person':
            return object.uid;
          default:
            return defaultDataIdFromObject(object); // fall back to default handling
        }
      }
    })
  });

  return client;
}
Example #2
Source File: CGraphQLClient.ts    From Cromwell with MIT License 6 votes vote down vote up
/** @internal */
    private async createClient() {
        let doneInit: (() => void) | undefined;
        this.initializePromise = new Promise<void>(done => doneInit = done);

        if (isServer()) {
            // If backend, try to find service secret key to make 
            // authorized requests to the API server.
            this.serviceSecret = await getServiceSecret();
        }

        const cache = new InMemoryCache();
        const link = createHttpLink({
            uri: this.getBaseUrl(),
            credentials: 'include',
            fetch: this.fetch,
            headers: this.serviceSecret && { 'Authorization': `Service ${this.serviceSecret}` },
        });

        this.apolloClient = new ApolloClient({
            cache: cache,
            link: link,
            name: 'cromwell-core-client',
            queryDeduplication: false,
            defaultOptions: {
                query: {
                    fetchPolicy: 'network-only',
                },
                watchQuery: {
                    fetchPolicy: 'cache-and-network',
                },
            },
        });

        doneInit?.();
        this.initializePromise = undefined;
    }
Example #3
Source File: apollo.ts    From storefront with MIT License 6 votes vote down vote up
export default function createClient({
  initialState = {},
}: { initialState?: NormalizedCacheObject } = {}) {
  if (apolloClient == null) {
    apolloClient = new ApolloClient({
      // eslint-disable-next-line unicorn/prefer-spread
      link: errorLink.concat(
        // eslint-disable-next-line unicorn/prefer-spread
        authLink.concat(
          // eslint-disable-next-line unicorn/prefer-spread
          afterware.concat(
            createHttpLink({
              uri: process.env.GRAPHQL_URL,
              credentials: 'include',
            }),
          ),
        ),
      ),
      cache: new InMemoryCache({ possibleTypes: introspectionResult.possibleTypes }).restore(
        initialState,
      ),
    });
  }
  return apolloClient;
}
Example #4
Source File: index.tsx    From amplication with Apache License 2.0 5 votes vote down vote up
httpLink = createHttpLink({
  uri: REACT_APP_DATA_SOURCE,
})
Example #5
Source File: graphqlDataProvider.ts    From amplication with Apache License 2.0 5 votes vote down vote up
httpLink = createHttpLink({
  uri: "/graphql",
})
Example #6
Source File: apollo.ts    From HoldemSolver with MIT License 5 votes vote down vote up
httpLink = createHttpLink({
    uri: `http://localhost:3535/graphql/query${localStorage.getItem('csrf') ? '?csrf=' + localStorage.getItem('csrf') : ''}`
})
Example #7
Source File: Shell.tsx    From dh-web with GNU General Public License v3.0 5 votes vote down vote up
Shell: FC<ShellProperties> = ({ children }: ShellProperties) => {

    // get the authentication token from local storage if it exists
    const authToken = useSelector(getAuthenticationToken);

    const bearerString = authToken && `Bearer ${authToken}`;
    // cross platform web socketing triage (tldr use node lib on server and web lib on browser)
    const webSocketImplementation = process.browser ? WebSocket : ws;

    const wsLink = new WebSocketLink({
        uri: "wss://api.dogehouse.online/graphql",
        options: {
            reconnect: true,
            lazy: true,
            timeout: 3000,
            connectionParams: {
                authorization: bearerString
            }
        },
        webSocketImpl: webSocketImplementation
    });

    const httpLink = createHttpLink({
        uri: "https://api.dogehouse.online/graphql",
    });

    const authLink = setContext((_, { headers }) => {
        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: bearerString,
            }
        };
    });

    const splitLink = split(
        ({ query }) => {
            const definition = getMainDefinition(query);
            return (
                definition.kind === "OperationDefinition" &&
                definition.operation === "subscription"
            );
        },
        wsLink,
        (authLink.concat(httpLink)),
    );

    const client = new ApolloClient({
        link: from([errorLink, splitLink]),
        cache: new InMemoryCache(),
    });

    return (
        <ThemeProvider theme={DarkTheme}>
            <ApolloProvider client={client}>
                <GlobalStyle />
                <Head>
                    <link rel="preconnect" href="https://fonts.gstatic.com" />
                    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet" />
                </Head>
                <Wrapper>
                    <NoSsr>
                        {
                            children
                        }
                    </NoSsr>
                </Wrapper>
            </ApolloProvider>
        </ThemeProvider>
    );
}
Example #8
Source File: index.tsx    From tinyhouse with MIT License 5 votes vote down vote up
httpLink = createHttpLink({
    uri: "/api",
})
Example #9
Source File: client.ts    From magento_react_native_graphql with MIT License 5 votes vote down vote up
export async function getApolloClient(): Promise<ApolloClient<any>> {
  if (_client) {
    return _client;
  }

  const cache = new InMemoryCache({
    possibleTypes,
    typePolicies: {
      Query: {
        fields: {
          products: {
            // Cache separate results based on
            // any of this field's arguments.
            keyArgs: ['search', 'filter'],
            // Concatenate the incoming list items with
            // the existing list items.
            merge(existing, incoming, { args: { currentPage } }) {
              if (currentPage === 1) {
                return incoming;
              }
              const _existing = existing ?? { items: [] };
              const _incoming = incoming ?? { items: [] };
              return {
                ..._existing,
                ..._incoming,
                items: [..._existing.items, ..._incoming.items],
              };
            },
          },
        },
      },
    },
  });

  const customerToken = await loadCustomerToken();

  if (customerToken !== null) {
    cache.writeQuery({
      query: IS_LOGGED_IN,
      data: {
        isLoggedIn: true,
      },
    });
  }

  const httpLink = createHttpLink({
    uri: `${magentoConfig.url}/graphql`,
  });

  const authLink = setContext(async (_, { headers }) => {
    // get the authentication token from local storage if it exists
    const token = await loadCustomerToken();
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token !== null ? `Bearer ${token}` : '',
      },
    };
  });

  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache,
  });

  _client = client;

  return client;
}
Example #10
Source File: data-service-generator.e2e-spec.ts    From amplication with Apache License 2.0 4 votes vote down vote up
describe("Data Service Generator", () => {
  let dockerComposeOptions: compose.IDockerComposeOptions;
  let port: number;
  let host: string;
  let customer: { id: string };
  let apolloClient: ApolloClient<any>;
  beforeAll(async () => {
    const directory = path.join(os.tmpdir(), "test-data-service");

    // Clean the temporary directory
    try {
      await fs.promises.rm(directory, { recursive: true });
    } catch {}
    await fs.promises.mkdir(directory);

    // Generate the test data service
    await generateTestDataService(directory, appInfo);

    port = await getPort();
    const dbPort = await getPort();
    host = `http://0.0.0.0:${port}`;

    const authLink = setContext((_, { headers }) => ({
      headers: {
        ...headers,
        authorization: APP_BASIC_AUTHORIZATION,
      },
    }));

    const errorLink = onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.map(({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
          )
        );

      if (networkError) console.log(`[Network error]: ${networkError}`);
    });

    const httpLink = createHttpLink({
      uri: `${host}/graphql`,
      fetch,
    });

    apolloClient = new ApolloClient({
      link: authLink.concat(errorLink).concat(httpLink),
      cache: new InMemoryCache(),
    });

    dockerComposeOptions = {
      cwd: directory,
      log: true,
      composeOptions: ["--project-name=e2e"],
      env: {
        ...process.env,
        POSTGRESQL_USER: POSTGRESQL_USER,
        POSTGRESQL_PASSWORD: POSTGRESQL_PASSWORD,
        POSTGRESQL_PORT: String(dbPort),
        SERVER_PORT: String(port),
        BCRYPT_SALT: "10",
        // See: https://www.docker.com/blog/faster-builds-in-compose-thanks-to-buildkit-support/
        COMPOSE_DOCKER_CLI_BUILD: "1",
        DOCKER_BUILDKIT: "1",
        JWT_SECRET_KEY: "Change_ME!!!",
        JWT_EXPIRATION: "2d",
      },
    };

    // Cleanup Docker Compose before run
    await down(dockerComposeOptions);

    await compose.upAll({
      ...dockerComposeOptions,
      commandOptions: ["--build", "--force-recreate"],
    });

    compose.logs([], { ...dockerComposeOptions, follow: true });

    console.info("Waiting for server to be ready...");
    await sleep(SERVER_START_TIMEOUT);
  });

  afterAll(async () => {
    await down(dockerComposeOptions);
  });
  test("check /api/health/live endpoint", async () => {
    const res = await fetch(`${host}/api/health/live`, {
      method: "GET",
    });
    expect(res.status === STATUS_OK);
  });

  test("check api/health/ready endpoint", async () => {
    const res = await fetch(`${host}/api/health/ready`, {
      method: "GET",
    });
    expect(res.status === STATUS_OK);
  });

  test("creates POST /api/login endpoint", async () => {
    const res = await fetch(`${host}/api/login`, {
      method: "POST",
      headers: {
        "Content-Type": JSON_MIME,
      },
      body: JSON.stringify({
        username: APP_USERNAME,
        password: APP_PASSWORD,
      }),
    });
    expect(res.status === STATUS_CREATED);
    expect(await res.json()).toEqual(
      expect.objectContaining({
        username: APP_USERNAME,
        roles: APP_DEFAULT_USER_ROLES,
      })
    );
  });

  test("creates POST /api/customers endpoint", async () => {
    const res = await fetch(`${host}/api/customers`, {
      method: "POST",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
      body: JSON.stringify(EXAMPLE_CUSTOMER),
    });
    expect(res.status === STATUS_CREATED);
    customer = await res.json();
    expect(customer).toEqual(
      expect.objectContaining({
        ...EXAMPLE_CUSTOMER,
        id: expect.any(String),
        createdAt: expect.any(String),
        updatedAt: expect.any(String),
      })
    );
  });

  test("creates PATCH /api/customers/:id endpoint", async () => {
    const customer = await (
      await fetch(`${host}/api/customers`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_CUSTOMER),
      })
    ).json();
    const res = await fetch(`${host}/api/customers/${customer.id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
      body: JSON.stringify(EXAMPLE_CUSTOMER_UPDATE),
    });
    expect(res.status === STATUS_OK);
  });

  test("handles PATCH /api/customers/:id for a non-existing id", async () => {
    const id = "nonExistingId";
    const res = await fetch(`${host}/api/customers/${id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
      body: JSON.stringify(EXAMPLE_CUSTOMER_UPDATE),
    });
    expect(res.status === NOT_FOUND);
  });

  test("creates DELETE /api/customers/:id endpoint", async () => {
    const customer = await (
      await fetch(`${host}/api/customers`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_CUSTOMER),
      })
    ).json();
    const res = await fetch(`${host}/api/customers/${customer.id}`, {
      method: "DELETE",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
    });
    expect(res.status === STATUS_OK);
  });

  test("handles DELETE /api/customers/:id for a non-existing id", async () => {
    const id = "nonExistingId";
    const res = await fetch(`${host}/api/customers/${id}`, {
      method: "DELETE",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
    });
    expect(res.status === NOT_FOUND);
  });

  test("creates GET /api/customers endpoint", async () => {
    const res = await fetch(`${host}/api/customers`, {
      headers: {
        Authorization: APP_BASIC_AUTHORIZATION,
      },
    });
    expect(res.status === STATUS_OK);
    const customers = await res.json();
    expect(customers).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          ...EXAMPLE_CUSTOMER,
          id: expect.any(String),
          createdAt: expect.any(String),
          updatedAt: expect.any(String),
        }),
      ])
    );
  });

  test("creates GET /api/customers/:id endpoint", async () => {
    const res = await fetch(`${host}/api/customers/${customer.id}`, {
      headers: {
        Authorization: APP_BASIC_AUTHORIZATION,
      },
    });

    expect(res.status === STATUS_OK);
    expect(await res.json()).toEqual(
      expect.objectContaining({
        ...EXAMPLE_CUSTOMER,
        id: expect.any(String),
        createdAt: expect.any(String),
        updatedAt: expect.any(String),
      })
    );
  });

  test("creates POST /api/organizations/:id/customers endpoint", async () => {
    const customer = await (
      await fetch(`${host}/api/customers`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_CUSTOMER),
      })
    ).json();

    const organization = await (
      await fetch(`${host}/api/organizations`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_ORGANIZATION),
      })
    ).json();

    const res = await fetch(
      `${host}/api/organizations/${organization.id}/customers`,
      {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify([
          {
            id: customer.id,
          },
        ]),
      }
    );
    expect(res.status).toBe(STATUS_CREATED);
    const data = await res.text();
    expect(data).toBe("");
  });

  test("creates DELETE /api/organizations/:id/customers endpoint", async () => {
    const customer = await (
      await fetch(`${host}/api/customers`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_CUSTOMER),
      })
    ).json();
    const organization = await (
      await fetch(`${host}/api/organizations`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_ORGANIZATION),
      })
    ).json();

    await fetch(`${host}/api/organizations/${organization.id}/customers`, {
      method: "POST",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
      body: JSON.stringify([
        {
          id: customer.id,
        },
      ]),
    });

    const res = await fetch(
      `${host}/api/organizations/${organization.id}/customers`,
      {
        method: "DELETE",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify([
          {
            id: customer.id,
          },
        ]),
      }
    );
    expect(res.status).toBe(STATUS_OK);
    const data = await res.text();
    expect(data).toBe("");
  });

  test("creates GET /api/organizations/:id/customers endpoint", async () => {
    const customer = await (
      await fetch(`${host}/api/customers`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_CUSTOMER),
      })
    ).json();
    const organization = await (
      await fetch(`${host}/api/organizations`, {
        method: "POST",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
        body: JSON.stringify(EXAMPLE_ORGANIZATION),
      })
    ).json();

    await fetch(`${host}/api/organizations/${organization.id}/customers`, {
      method: "POST",
      headers: {
        "Content-Type": JSON_MIME,
        Authorization: APP_BASIC_AUTHORIZATION,
      },
      body: JSON.stringify([
        {
          id: customer.id,
        },
      ]),
    });

    const res = await fetch(
      `${host}/api/organizations/${organization.id}/customers`,
      {
        method: "GET",
        headers: {
          "Content-Type": JSON_MIME,
          Authorization: APP_BASIC_AUTHORIZATION,
        },
      }
    );
    expect(res.status).toBe(STATUS_OK);
    const data = await res.json();
    expect(data).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          ...EXAMPLE_CUSTOMER,
          id: customer.id,
          createdAt: expect.any(String),
          updatedAt: expect.any(String),
          organization: {
            id: organization.id,
          },
        }),
      ])
    );
  });

  test("adds customers to root query", async () => {
    expect(
      await apolloClient.query({
        query: gql`
          {
            customers(where: {}) {
              id
              createdAt
              updatedAt
              email
              firstName
              lastName
            }
          }
        `,
      })
    ).toEqual(
      expect.objectContaining({
        data: {
          customers: expect.arrayContaining([
            expect.objectContaining({
              ...omit(EXAMPLE_CUSTOMER, ["organization"]),
              id: customer.id,
              createdAt: expect.any(String),
              updatedAt: expect.any(String),
            }),
          ]),
        },
      })
    );
  });

  //TODO add test if not connect to db send api/health/ready status 503
});