How to use apollo-server-env - 10 common examples

To help you get started, we’ve selected a few apollo-server-env examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apollographql / apollo-server / packages / apollo-server-testing / src / ApolloServer.ts View on Github external
public async execute(
    operation: string,
    variables?: { [name: string]: string },
    additionalHeaders?: object,
  ) {
    const body = {
      query: operation,
      variables,
    };
    const headers = new Headers({ 'Content-Type': 'application/json' });

    if (additionalHeaders) {
      for (const [name, value] of new Headers(additionalHeaders)) {
        headers.append(name, value);
      }
    }
    const request = new Request('http://localhost', {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
    });

    // create the options and run the operation
    const options = this.createGraphQLServerOptions.bind(this);
    const response = await graphqlTesting(options)(request);
github apollographql / apollo-server / packages / apollo-server-testing / src / ApolloServer.ts View on Github external
operation: string,
    variables?: { [name: string]: string },
    additionalHeaders?: object,
  ) {
    const body = {
      query: operation,
      variables,
    };
    const headers = new Headers({ 'Content-Type': 'application/json' });

    if (additionalHeaders) {
      for (const [name, value] of new Headers(additionalHeaders)) {
        headers.append(name, value);
      }
    }
    const request = new Request('http://localhost', {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
    });

    // create the options and run the operation
    const options = this.createGraphQLServerOptions.bind(this);
    const response = await graphqlTesting(options)(request);

    // parse response and return
    const contentType = response.headers.get('Content-Type');
    if (contentType && contentType.startsWith('application/json')) {
      return response.json();
    } else {
      return response.text();
    }
github apollographql / apollo-server / packages / apollo-server-lambda / src / ApolloServer.ts View on Github external
return (
      event: APIGatewayProxyEvent,
      context: LambdaContext,
      callback: APIGatewayProxyCallback,
    ) => {
      // We re-load the headers into a Fetch API-compatible `Headers`
      // interface within `graphqlLambda`, but we still need to respect the
      // case-insensitivity within this logic here, so we'll need to do it
      // twice since it's not accessible to us otherwise, right now.
      const eventHeaders = new Headers(event.headers);

      // Make a request-specific copy of the CORS headers, based on the server
      // global CORS headers we've set above.
      const requestCorsHeaders = new Headers(corsHeaders);

      if (cors && cors.origin) {
        const requestOrigin = eventHeaders.get('origin');
        if (typeof cors.origin === 'string') {
          requestCorsHeaders.set('access-control-allow-origin', cors.origin);
        } else if (
          requestOrigin &&
          (typeof cors.origin === 'boolean' ||
            (Array.isArray(cors.origin) &&
              requestOrigin &&
              cors.origin.includes(requestOrigin)))
        ) {
          requestCorsHeaders.set('access-control-allow-origin', requestOrigin);
        }

        const requestAccessControlRequestHeaders = eventHeaders.get(
github apollographql / apollo-server / packages / apollo-gateway / src / executeQueryPlan.ts View on Github external
async function sendOperation(
    context: ExecutionContext,
    operation: OperationDefinitionNode,
    variables: Record,
  ): Promise {
    const source = print(operation);
    // We declare this as 'any' because it is missing url and method, which
    // GraphQLRequest.http is supposed to have if it exists.
    let http: any;

    // If we're capturing a trace for Engine, then save the operation text to
    // the node we're building and tell the federated service to include a trace
    // in its response.
    if (traceNode) {
      http = {
        headers: new Headers({ 'apollo-federation-include-trace': 'ftv1' }),
      };
      if (
        context.requestContext.metrics &&
        context.requestContext.metrics.startHrTime
      ) {
        traceNode.sentTimeOffset = durationHrTimeToNanos(
          process.hrtime(context.requestContext.metrics.startHrTime),
        );
      }
      traceNode.sentTime = dateToProtoTimestamp(new Date());
    }

    const response = await service.process({
      request: {
        query: source,
        variables,
github apollographql / apollo-server / packages / apollo-server-lambda / src / ApolloServer.ts View on Github external
return (
      event: APIGatewayProxyEvent,
      context: LambdaContext,
      callback: APIGatewayProxyCallback,
    ) => {
      // We re-load the headers into a Fetch API-compatible `Headers`
      // interface within `graphqlLambda`, but we still need to respect the
      // case-insensitivity within this logic here, so we'll need to do it
      // twice since it's not accessible to us otherwise, right now.
      const eventHeaders = new Headers(event.headers);

      // Make a request-specific copy of the CORS headers, based on the server
      // global CORS headers we've set above.
      const requestCorsHeaders = new Headers(corsHeaders);

      if (cors && cors.origin) {
        const requestOrigin = eventHeaders.get('origin');
        if (typeof cors.origin === 'string') {
          requestCorsHeaders.set('access-control-allow-origin', cors.origin);
        } else if (
          requestOrigin &&
          (typeof cors.origin === 'boolean' ||
            (Array.isArray(cors.origin) &&
              requestOrigin &&
              cors.origin.includes(requestOrigin)))
        ) {
github apollographql / apollo-server / packages / apollo-server-lambda / src / ApolloServer.ts View on Github external
public createHandler({ cors, onHealthCheck }: CreateHandlerOptions = { cors: undefined, onHealthCheck: undefined }) {
    // We will kick off the `willStart` event once for the server, and then
    // await it before processing any requests by incorporating its `await` into
    // the GraphQLServerOptions function which is called before each request.
    const promiseWillStart = this.willStart();

    const corsHeaders = new Headers();

    if (cors) {
      if (cors.methods) {
        if (typeof cors.methods === 'string') {
          corsHeaders.set('access-control-allow-methods', cors.methods);
        } else if (Array.isArray(cors.methods)) {
          corsHeaders.set(
            'access-control-allow-methods',
            cors.methods.join(','),
          );
        }
      }

      if (cors.allowedHeaders) {
        if (typeof cors.allowedHeaders === 'string') {
          corsHeaders.set('access-control-allow-headers', cors.allowedHeaders);
github apollographql / apollo-server / packages / apollo-server-cloud-functions / src / googleCloudApollo.ts View on Github external
const graphqlHandler: any = (req: Request, res: Response): void => {
    const hasPostBody = req.body && Object.keys(req.body).length > 0;
    if (req.method === 'POST' && !hasPostBody) {
      res.status(500).send('POST body missing.');
      return;
    }

    runHttpQuery([req, res], {
      method: req.method,
      options: options,
      query: hasPostBody ? req.body : (req.query as any),
      request: {
        url: req.url,
        method: req.method,
        headers: new Headers(req.headers as any), // ? Check if this actually works
      },
    }).then(
      ({ graphqlResponse, responseInit }) => {
        res
          .status(200)
          .set(responseInit.headers)
          .send(graphqlResponse);
      },
      (error: HttpQueryError) => {
        if ('HttpQueryError' !== error.name) {
          res.status(500).send(error);
          return;
        }
        res
          .status(error.statusCode)
          .set(error.headers)
github apollographql / apollo-server / packages / apollo-datasource-rest / src / HTTPCache.ts View on Github external
);
    }

    const { policy: policyRaw, ttlOverride, body } = JSON.parse(entry);

    const policy = CachePolicy.fromObject(policyRaw);
    // Remove url from the policy, because otherwise it would never match a request with a custom cache key
    policy._url = undefined;

    if (
      (ttlOverride && policy.age() < ttlOverride) ||
      (!ttlOverride &&
        policy.satisfiesWithoutRevalidation(policyRequestFrom(request)))
    ) {
      const headers = policy.responseHeaders();
      return new Response(body, {
        url: policy._url,
        status: policy._status,
        headers,
      });
    } else {
      const revalidationHeaders = policy.revalidationHeaders(
        policyRequestFrom(request),
      );
      const revalidationRequest = new Request(request, {
        headers: revalidationHeaders,
      });
      const revalidationResponse = await this.httpFetch(revalidationRequest);

      const { policy: revalidatedPolicy, modified } = policy.revalidatedPolicy(
        policyRequestFrom(revalidationRequest),
        policyResponseFrom(revalidationResponse),
github apollographql / apollo-server / packages / apollo-datasource-rest / src / HTTPCache.ts View on Github external
const body = await response.text();
    const entry = JSON.stringify({
      policy: policy.toObject(),
      ttlOverride,
      body,
    });

    await this.keyValueCache.set(cacheKey, entry, {
      ttl,
    });

    // We have to clone the response before returning it because the
    // body can only be used once.
    // To avoid https://github.com/bitinn/node-fetch/issues/151, we don't use
    // response.clone() but create a new response from the consumed body
    return new Response(body, {
      url: response.url,
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
    });
  }
}
github hanpama / girin / packages / framework / src / __tests__ / testenv.ts View on Github external
export async function query(doc: string, headers = {}): Promise<{ data: any, errors: any }> {
  const res = await fetch(url, {
    method: 'POST',
    headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
    body: JSON.stringify({ query: doc }),
  });
  return res.json();
}

apollo-server-env

This package is used internally by Apollo Server and not meant to be consumed directly.

MIT
Latest version published 2 years ago

Package Health Score

72 / 100
Full package analysis