Skip to content

Commit

Permalink
feat(utils): 新增 isCuid
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Dec 8, 2023
1 parent 7627b5a commit 0241337
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/utils/isCuid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { isCuid } from './isCuid'

describe('isCuid', () => {
test('ok', () => {
expect(isCuid('cjld2cjxh0000qzrmn831i7rn')).toBeTrue()
expect(isCuid('cjld2cyuq0000t3rmniod1foy')).toBeTrue()

expect(isCuid('1')).toBeFalse()
// @ts-expect-error
expect(isCuid(2)).toBeFalse()
// @ts-expect-error
expect(isCuid(null)).toBeFalse()
// @ts-expect-error
expect(isCuid([])).toBeFalse()
})
})
26 changes: 26 additions & 0 deletions src/utils/isCuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const re = /^c[0-9a-z]+$/

/**
* 检测传入值是否是 Cuid。
*
* @param value 要检测的值
* @returns 返回检测结果
* @example
* ```typescript
* isCuid('1') // => false
* isCuid('cjld2cjxh0000qzrmn831i7rn') // => true
* ```
* @see https://github.com/paralleldrive/cuid
*/
export function isCuid(value: string): boolean {
return (
!!value &&
typeof value === 'string' &&
// 注意: Cuid长度并不保证是固定的25位
// https://github.com/paralleldrive/cuid/issues/51
value.length >= 20 &&
value.length <= 30 &&
value[0] === 'c' &&
re.test(value)
)
}

0 comments on commit 0241337

Please sign in to comment.