strapi-utils
Page summary:
@strapi/utils包提供了用于 Strapi 核心的共享辅助函数,也可用于自定义代码。它包括错误类、环境变量辅助、钩子工厂、类型解析、字符串和文件工具以及异步辅助。
@strapi/utils 包(import { ... } from '@strapi/utils')包含 Strapi 内部使用的实用函数,但你也可以在自己的 controllers、services、policies、middlewares 和 lifecycle hooks 中使用这些函数。
🌐 The @strapi/utils package (import { ... } from '@strapi/utils') contains utility functions that Strapi uses internally but that you can also use in your own controllers, services, policies, middlewares, and lifecycle hooks.
本页面的各部分按导出名称的字母顺序组织。使用右侧的目录可直接跳转到所需的工具。
🌐 Sections on this page are organized alphabetically by export name. Use the table of contents on the right to jump directly to the utility you need.
本页面的错误类别部分扩展了专门的错误处理页面中的错误处理文档。
🌐 The error classes section of this page expands on the error handling documentation found in the dedicated Error handling page.
async
async 命名空间提供异步实用函数。它的导入方式如下:
🌐 The async namespace provides asynchronous utility functions. It is imported as follows:
const { async } = require('@strapi/utils');
以下功能可用:
🌐 The following functions are available:
| 功能 | 描述 |
|---|---|
async.map(iterable, mapper, options?) | 使用 p-map 的并行映射。通过选项中的 concurrency 设置并行度。 |
async.pipe(...fns) | 组合函数:第一个函数使用原始参数运行,每个后续函数接收上一个函数的返回值。返回一个 Promise。 |
async.reduce(array)(iteratee, initialValue?) | 对数组进行异步归约。分两步调用:先传入数组,然后传入迭代函数和可选的初始值。迭代函数接收 (accumulator, item, index)。 |
以下示例使用 pipe 来组合异步函数,并使用 reduce 来累积值:
🌐 The following example uses pipe to compose async functions, and reduce to accumulate values:
const { async: asyncUtils } = require('@strapi/utils');
// Compose async functions into a pipeline
const result = await asyncUtils.pipe(
fetchUser,
enrichWithProfile,
formatResponse
)(userId);
// Reduce an array asynchronously (note the curried call)
const total = await asyncUtils.reduce([1, 2, 3])(
async (sum, n) => sum + n,
0
); // 6
contentTypes
contentTypes 命名空间公开了用于处理 Strapi 内容类型模式的常量和辅助函数。它的导入方式如下:
🌐 The contentTypes namespace exposes constants and helper functions for working with Strapi content-type schemas. It is imported as follows:
const { contentTypes } = require('@strapi/utils');
常量
🌐 Constants
以下常量可用:
🌐 The following constants are available:
| 常量 | 值 | 描述 |
|---|---|---|
ID_ATTRIBUTE | 'id' | 主键字段名 |
DOC_ID_ATTRIBUTE | 'documentId' | 文档标识字段名 |
PUBLISHED_AT_ATTRIBUTE | 'publishedAt' | 发布时间戳字段名 |
FIRST_PUBLISHED_AT_ATTRIBUTE | 'firstPublishedAt' | 首次发布时间戳字段名 |
CREATED_BY_ATTRIBUTE | 'createdBy' | 创建者引用字段名 |
UPDATED_BY_ATTRIBUTE | 'updatedBy' | 最后编辑者引用字段名 |
CREATED_AT_ATTRIBUTE | 'createdAt' | 创建时间戳字段名 |
UPDATED_AT_ATTRIBUTE | 'updatedAt' | 更新时间戳字段名 |
SINGLE_TYPE | 'singleType' | 单类型标识符 |
COLLECTION_TYPE | 'collectionType' | 集合类型标识符 |
属性检查功能
🌐 Attribute inspection functions
以下函数用于检查单个属性的类型:
🌐 The following functions check the type of a single attribute:
| 功能 | 描述 |
|---|---|
isComponentAttribute(attribute) | 检查属性是否为组件或动态区域(两者都返回 true;使用 isDynamicZoneAttribute 进行区分) |
isDynamicZoneAttribute(attribute) | 检查属性是否为动态区域 |
isMediaAttribute(attribute) | 检查属性是否为媒体字段 |
isMorphToRelationalAttribute(attribute) | 检查属性是否为多态关联 |
isRelationalAttribute(attribute) | 检查属性是否为关联 |
isScalarAttribute(attribute) | 检查属性是否为标量值 |
isTypedAttribute(attribute, type) | 检查属性是否具有特定类型 |
模式检查函数
🌐 Schema inspection functions
以下函数会检查整个内容类型模式:
🌐 The following functions inspect an entire content-type schema:
| 功能 | 描述 |
|---|---|
getCreatorFields(schema) | 返回模式中存在的创建者字段(createdBy、updatedBy) |
getNonWritableAttributes(schema) | 返回无法写入的字段名称 |
getScalarAttributes(schema) | 返回标量值的属性 |
getTimestamps(schema) | 返回模式中存在的时间戳字段(createdAt、updatedAt) |
getVisibleAttributes(schema) | 返回未标记为不可见的模式属性 |
getWritableAttributes(schema) | 返回可以写入的字段名称 |
hasDraftAndPublish(schema) | 检查模式是否启用了草稿和发布 |
isWritableAttribute(schema, attributeName) | 检查特定属性是否可写 |
以下示例遍历内容类型的属性以查找关系和可写字段:
🌐 The following example iterates over a content type's attributes to find relations and writable fields:
const { contentTypes } = require('@strapi/utils');
const articleSchema = strapi.contentType('api::article.article');
// List all relation fields
for (const [name, attribute] of Object.entries(articleSchema.attributes)) {
if (contentTypes.isRelationalAttribute(attribute)) {
console.log(`${name} is a relation`);
}
}
// Get only the fields that can be written to
const writableFields = contentTypes.getWritableAttributes(articleSchema);
// Check if draft and publish is enabled
if (contentTypes.hasDraftAndPublish(articleSchema)) {
console.log('This content type supports drafts');
}
env
一个用于读取环境变量并进行类型安全解析的辅助函数。env 函数返回原始字符串值,而它的方法则将该值解析为特定类型。其导入方式如下:
🌐 A helper function to read environment variables with type-safe parsing. The env function returns the raw string value, while its methods parse the value to a specific type. It is imported as follows:
const { env } = require('@strapi/utils');
// or in TypeScript: import { env } from '@strapi/utils';
env 辅助工具可以直接调用,也可以使用以下类型化方法调用:
🌐 The env helper can be called directly or with the following typed methods:
| 方法 | 返回类型 | 描述 |
|---|---|---|
env(key) | string | undefined | 返回原始值 |
env(key, default) | string | 返回原始值或默认值 |
env.array(key, default?) | string[] | undefined | 按逗号拆分,修剪值,去掉周围的 [] 和双引号 |
env.bool(key, default?) | boolean | undefined | 'true' 返回 true,其他任何返回 false |
env.date(key, default?) | Date | undefined | 使用 new Date() 解析 |
env.float(key, default?) | number | undefined | 解析为浮点数 (parseFloat) |
env.int(key, default?) | number | undefined |