Skip to content

最后修改时间模式

您可创建自定义模式来显示内容的最后修改时间。这可以基于:

  • 文件状态信息
  • Git 时间戳

基于文件状态信息

创建基于文件状态信息的时间戳模式。

ts
import { stat } from 'fs/promises'
import { defineSchema } from 'velite'

const timestamp = defineSchema(() =>
  s
    .custom<string | undefined>(i => i === undefined || typeof i === 'string')
    .transform<string>(async (value, { meta, addIssue }) => {
      if (value != null) {
        addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the file modified timestamp' })
      }

      const stats = await stat(meta.path)
      return stats.mtime.toISOString()
    })
)

在您的模式中使用:

ts
const posts = defineCollection({
  // ...
  schema: {
    // ...
    lastModified: timestamp()
  }
})

基于 Git 时间戳

ts
import { exec } from 'child_process'
import { promisify } from 'util'
import { defineSchema } from 'velite'

const execAsync = promisify(exec)

const timestamp = defineSchema(() =>
  s
    .custom<string | undefined>(i => i === undefined || typeof i === 'string')
    .transform<string>(async (value, { meta, addIssue }) => {
      if (value != null) {
        addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --format=%cd`' })
      }
      const { stdout } = await execAsync(`git log -1 --format=%cd ${meta.path}`)
      return new Date(stdout || Date.now()).toISOString()
    })
)

在您的模式中使用:

ts
const posts = defineCollection({
  // ...
  schema: {
    // ...
    lastModified: timestamp()
  }
})

Distributed under the MIT License.