about summary refs log tree commit diff
path: root/src/types/bsky/index.ts
blob: d482f9515bee81afb8f628fb29b3e840935ac956 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import {type ValidationResult} from '@atproto/lexicon'

export * as post from '#/types/bsky/post'
export * as profile from '#/types/bsky/profile'
export * as starterPack from '#/types/bsky/starterPack'

/**
 * Fast type checking without full schema validation, for use with data we
 * trust, or for non-critical path use cases. Why? Our SDK's `is*` identity
 * utils do not assert the type of the entire object, only the `$type` string.
 *
 * For full validation of the object schema, use the `validate` export from
 * this file.
 *
 * Usage:
 * ```ts
 * import * as bsky from '#/types/bsky'
 *
 * if (bsky.dangerousIsType<AppBskyFeedPost.Record>(item, AppBskyFeedPost.isRecord)) {
 *   // `item` has type `$Typed<AppBskyFeedPost.Record>` here
 * }
 * ```
 */
export function dangerousIsType<R extends {$type?: string}>(
  record: unknown,
  identity: <V>(v: V) => v is V & {$type: NonNullable<R['$type']>},
): record is R {
  return identity(record)
}

/**
 * Fully validates the object schema, which has a performance cost.
 *
 * For faster checks with data we trust, like that from our app view, use the
 * `dangerousIsType` export from this same file.
 *
 * Usage:
 * ```ts
 * import * as bsky from '#/types/bsky'
 *
 * if (bsky.validate(item, AppBskyFeedPost.validateRecord)) {
 *   // `item` has type `$Typed<AppBskyFeedPost.Record>` here
 * }
 * ```
 */
export function validate<R extends {$type?: string}>(
  record: unknown,
  validator: (v: unknown) => ValidationResult<R>,
): record is R {
  return validator(record).success
}