You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Strapi v4中如何禁用CRUD以外的GraphQL查询与变更?

如何在Strapi v4.3.4的GraphQL插件中禁用非ShadowCRUD的查询与变更

针对你需要屏蔽uploadFile、login这类非ShadowCRUD操作的需求,有三种实用方案,根据你的场景选择即可:

方案一:通过Schema过滤精准移除指定操作

在src/index.js中利用Strapi GraphQL插件的扩展机制,直接过滤掉不需要的Query和Mutation字段:

module.exports = {
  register({ strapi }) {
    const extension = ({ nexus }) => ({
      schema: {
        filters: {
          Query: {
            // 只保留产品、分类的查询,其他全部移除
            keep: ['products', 'product', 'categories', 'category'],
            // 或者用remove指定要删除的字段:
            // remove: ['uploadFile', 'uploadFiles', 'i18Nlocale', 'usersPermissionsUser', 'login']
          },
          Mutation: {
            // 移除所有不需要的变更操作
            remove: ['uploadFile', 'register', 'login', 'createUsersPermissionsUser']
          }
        }
      }
    });

    strapi.plugin('graphql').service('extension').use(extension);
  },
};

说明:keep规则是"白名单"模式,只保留指定字段;remove是"黑名单"模式,移除指定字段,两种模式二选一即可。这种方式不用修改其他配置,适合需要保留部分默认操作的场景。

方案二:完全自定义GraphQL Schema

如果需要彻底控制对外暴露的API结构,可以完全自定义Schema,只定义你需要的查询和类型:

  1. 在项目根目录创建src/graphql/schema.graphql,写入自定义Schema:
type Query {
  products: [Product]
  product(id: ID!): Product
  categories: [Category]
  category(id: ID!): Category
}

type Product {
  id: ID!
  title: String
  description: String
  category: Category
}

type Category {
  id: ID!
  name: String
  products: [Product]
}
  1. 在src/index.js中加载自定义Schema并编写解析器:
module.exports = {
  register({ strapi }) {
    strapi.plugin('graphql').service('extension').use({
      typeDefs: strapi.fs.readFileSync('./src/graphql/schema.graphql', 'utf8'),
      resolvers: {
        Query: {
          products: async () => strapi.db.query('api::product.product').findMany(),
          product: async (_, { id }) => strapi.db.query('api::product.product').findOne({ where: { id } }),
          categories: async () => strapi.db.query('api::category.category').findMany(),
          category: async (_, { id }) => strapi.db.query('api::category.category').findOne({ where: { id } })
        }
      }
    });
  },
};

说明:这种方式会完全替换默认的GraphQL Schema,所有未定义的操作都会被屏蔽,适合对API安全性要求极高的场景。

方案三:直接禁用整个模块的GraphQL支持

如果不需要Upload、Users-Permissions、i18n这些模块的GraphQL接口,可以直接在插件配置中关闭它们的GraphQL功能:

修改config/plugins.js:

module.exports = ({ env }) => ({
  // 其他插件配置
  'users-permissions': {
    config: {
      graphql: {
        enabled: false,
      },
    },
  },
  upload: {
    config: {
      graphql: {
        enabled: false,
      },
    },
  },
  i18n: {
    config: {
      graphql: {
        enabled: false,
      },
    },
  },
});

说明:这是最简便的方案,直接关闭整个模块的GraphQL暴露,适合完全不需要这些模块对外提供API的情况。

内容的提问来源于stack exchange,提问作者Abdullah Al Nahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:18:20