Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "apollo-server-env in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-server-env' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

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);
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();
    }
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(
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,
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)))
        ) {
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);
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)
);
    }

    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),
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,
    });
  }
}
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();
}

Is your System Free of Underlying Vulnerabilities?
Find Out Now