-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypeguards.ts
More file actions
73 lines (60 loc) · 2.1 KB
/
typeguards.ts
File metadata and controls
73 lines (60 loc) · 2.1 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { Bytes, Timestamp } from 'firebase/firestore';
import { EncryptedField, List, Note, UserData } from '@/lib/types';
function objectTypeGuard(obj: unknown): obj is Record<string, unknown> {
return typeof obj === 'object' && obj !== null;
}
export function firebaseErrorTypeGuard(
error: unknown,
): error is { code: string; message: string } {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
typeof error.code === 'string' &&
'message' in error &&
typeof error.message === 'string'
);
}
export function encryptedFieldTypeGuard(obj: unknown): obj is EncryptedField {
if (
typeof obj === 'object' &&
obj !== null &&
'iv' in obj &&
'data' in obj &&
obj.iv instanceof Bytes &&
obj.data instanceof Bytes
) {
return true;
}
return false;
}
export function userDataTypeGuard(obj: unknown): obj is UserData {
if (!objectTypeGuard(obj)) return false;
const encryptedUserKey = obj.encryptedUserKey;
const salt = obj.salt;
const validEncryptedUserKey =
typeof encryptedUserKey === 'string' ||
encryptedFieldTypeGuard(encryptedUserKey);
const validSalt =
Array.isArray(salt) && salt.every((item) => typeof item === 'number');
return validEncryptedUserKey && validSalt;
}
export function noteTypeGuard(obj: unknown): obj is Note {
if (!objectTypeGuard(obj)) return false;
if (typeof obj.id !== 'string') return false;
if (!(obj.createdAt instanceof Timestamp)) return false;
if (obj.editedAt !== undefined && !(obj.editedAt instanceof Timestamp))
return false;
if (obj.userId !== undefined && typeof obj.userId !== 'string') return false;
if (typeof obj.title !== 'string') return false;
if (typeof obj.content !== 'string') return false;
if (typeof obj.listId !== 'string') return false;
return true;
}
export function listTypeGuard(obj: unknown): obj is List {
if (!objectTypeGuard(obj)) return false;
if (typeof obj.id !== 'string') return false;
if (typeof obj.name !== 'string') return false;
if (obj.userId !== undefined && typeof obj.userId !== 'string') return false;
return true;
}