How to use graphql-middleware - 10 common examples

To help you get started, we’ve selected a few graphql-middleware 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 Canner / graphql-i18n / test / i18nMiddleware.spec.ts View on Github external
const resolvers = {
      Query: {
        book: () => ({ id, ...dataEn }),
        books: () => ([{ id, ...dataEn }]),
      },
      Book: {
        name: () => 'just test',
      },
    };
    const typeConfig = makeExecutableSchema({
      typeDefs,
      resolvers,
    });

    const schemaWithPermissions = applyMiddleware(typeConfig, this.i18n.middleware());
    // Execution
    const query = `
      query {
        book @locale(lang: "zh") {
          name
          author {
            name
          }
        }
        books @locale(lang: "zh") {
          name
          author {
            name
          }
        }
      }
github Canner / graphql-rbac / test / rbac.spec.ts View on Github external
},
    };
    const schema = makeExecutableSchema({
      typeDefs,
      resolvers,
    });

    const roles = ['ADMIN', 'DEVELOPER'];
    const roleSchema = {
      Obj: ['ADMIN', 'DEVELOPER'],
    };
    const getUser = () => ({ role: 'ADMIN' });

    const rbac = new RBAC({roles, schema: roleSchema, getUser});

    const schemaWithPermissions = applyMiddleware(schema, rbac.middleware());
    // Execution
    const query = `
      query {
        test {
          name
        }
      }
    `;
    const adminRes = await graphql(schemaWithPermissions, query, {}, { user: { role: 'ADMIN' } });
    const developerRes = await graphql(schemaWithPermissions, query, {}, { user: { role: 'DEVELOPER' } });

    expect(adminRes.data).to.be.eql({
      test: { name: 'pass' },
    });
    expect(developerRes.data).to.be.eql({
      test: { name: 'pass' },
github frandiox / vue-graphql-enterprise-boilerplate / server / src / apollo-server.js View on Github external
}
) {
  const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
    schemaDirectives,
    directiveResolvers,
    resolverValidationOptions: {
      requireResolversForResolveType: false,
    },
  })

  // Apollo server options
  const options = {
    ...apolloServerOptions,
    schema: applyGraphQLMiddleware(schema, ...graphqlMiddlewares),
    tracing: true,
    cacheControl: true,
    engine: engineKey ? { apiKey: engineKey } : false,
    dataSources,
    // Resolvers context in POST requests
    context: async ({ req, connection }) => {
      let contextData
      try {
        if (connection) {
          contextData = { ...connection.context }
        } else {
          contextData = await context({ req, request: req })
        }
      } catch (error) {
        logger.error(error)
        throw error
github Canner / canner / packages / graphql-server / src / app.ts View on Github external
rootNode,
      models,
      dataSources,
      scalars: {
        JSON: GraphQLJSON,
        DateTime: GraphQLDateTime,
      },
      plugins: config.plugins,
    });

    const { typeDefs, resolvers } = gqlify.createApolloConfig();
    const schema = makeExecutableSchema({
      typeDefs: typeDefs as any,
      resolvers
    });
    const schemaWithMiddleware = applyMiddleware(schema, readOnlyMiddleware);

    // context
    const context = config.context || createContext(config);

    this.apolloServer = new ApolloServer({
      debug: true,
      playground: config.graphqlPlayground,
      schema: schemaWithMiddleware as any,
      formatError: (error: any) => {
        return apolloErrorHandler(error, this.logger);
      },
      context,
    });
  }
github webiny / webiny-js / packages / api / src / createHandler.js View on Github external
const middlewarePlugins = plugins.byType("graphql-middleware");
    for (let i = 0; i < middlewarePlugins.length; i++) {
        let plugin = middlewarePlugins[i];
        const middleware =
            typeof plugin.middleware === "function"
                ? await plugin.middleware({ plugins })
                : plugin.middleware;
        if (Array.isArray(middleware)) {
            registeredMiddleware.push(...middleware);
        } else {
            registeredMiddleware.push(middleware);
        }
    }

    if (registeredMiddleware.length) {
        schema = applyMiddleware(schema, ...registeredMiddleware);
    }

    addSchemaLevelResolveFunction(schema, async (root, args, context, info) => {
        // Make sure we do not block this resolver from processing subsequent requests!
        // This is something that is baked into the graphql-tools and cannot be avoided another way.
        delete info.operation["__runAtMostOnce"];

        // Process `graphql-context` plugins
        const ctxPlugins = plugins.byType("graphql-context");
        for (let i = 0; i < ctxPlugins.length; i++) {
            if (typeof ctxPlugins[i].preApply === "function") {
                await ctxPlugins[i].preApply(context);
            }
        }

        for (let i = 0; i < ctxPlugins.length; i++) {
github SolidZORO / leaa / packages / leaa-api / src / modules / graphql / graphql.service.ts View on Github external
      transformSchema: (schema: any): any => applyMiddleware(schema, permissionConfig.permissions),
      context: async (ctx: { req: Request }) => ({
github revskill10 / next-template / packages / server / create-graphql-server.js View on Github external
async function makeSchema(adminLinks) {
  let reportingSchema = await getRemoteSchema(adminLinks['reportingService'])
  
  if (urlMap['reportingService'].permissions) {
    reportingSchema = applyMiddleware(reportingSchema, urlMap['reportingService'].permissions)
  }
  
  let userSchema = await getRemoteSchema(adminLinks['userService'])
  if (urlMap['userService'].permissions) {
    userSchema = applyMiddleware(reportingSchema, urlMap['userService'].permissions)
  }
  const eduSchema = await soapGraphqlSchema(process.env.EDU_URL)
  let cmsSchema = await getRemoteSchema(adminLinks['cmsService'])
  if (urlMap['cmsService'].permissions) {
    cmsSchema = applyMiddleware(graphSchema, urlMap['cmsService'].permissions)
  }
  
  let localSchema = importSchema(__dirname + '/typedefs/schema.graphql')
  const resolvers = require('./resolvers')
  return mergeSchemas({
    schemas: [
      userSchema, 
      reportingSchema,
      eduSchema,
      cmsSchema,
      localSchema,
github andrewnaeve / Full-Stack-Docker / api / src / graphql / schema.js View on Github external
_empty: String
  }
`;

const Mutation = gql`
  type Mutation {
    _empty: String
  }
`;

const schema = makeExecutableSchema({
  typeDefs: [Query, Mutation, AuthTypes],
  resolvers: merge(authResolvers)
});

const schemaWithMiddleware = applyMiddleware(schema, permissions);

export default schemaWithMiddleware;
github Canner / graphql-i18n / src / index.ts View on Github external
: leafResult;
      } else if (!isNil(i18nObj)) {
        return {
          ...result,
          __i18n: i18nObj,
          __i18nLastPath: i18nLastPath,
        };
      }

      return result;
    };

    function generateMiddleware(): IMiddlewareFunction {
      return i18nMiddleware;
    }
    return middleware(generateMiddleware);
  }

graphql-middleware

GraphQL Middleware done right!

MIT
Latest version published 1 year ago

Package Health Score

63 / 100
Full package analysis