@prismicio/types-internal
Version:
Prismic types for Custom Types and Prismic Data
40 lines (33 loc) • 1.21 kB
text/typescript
import { isRight } from "fp-ts/lib/Either"
import * as t from "io-ts"
import { v4 as uuid, validate as validateUuid } from "uuid"
import { FieldContentType, FieldType } from "./fields"
type WithFieldType = WithContentType & { type: FieldType }
export function hasFieldContentType(obj: unknown): obj is WithFieldType {
return (
hasContentType(obj) &&
obj.__TYPE__ === FieldContentType &&
(obj as WithFieldType)?.type !== undefined &&
typeof (obj as WithFieldType).type === "string" &&
isRight(FieldType.decode((obj as WithFieldType).type))
)
}
type WithContentType = { __TYPE__: string }
export function hasContentType(obj: unknown): obj is WithContentType {
return typeof obj === "object" && obj !== null && "__TYPE__" in obj
}
const isUuid = (input: unknown): input is string =>
typeof input === "string" && validateUuid(input)
const uuidWithFallback = new t.Type<string, string, unknown>(
"UUID",
isUuid,
(u, c) => {
if (typeof u === "undefined") return t.success(uuid())
if (isUuid(u)) return t.success(u)
return t.failure(u, c)
},
t.identity,
)
export function withKey<C extends t.Mixed>(codec: C) {
return t.intersection([t.strict({ key: uuidWithFallback }), codec])
}