スキーマレスなFirestoreにTypeScriptの型でモデリング
code:models/publisher.ts
export type Publisher = {
id?: string;
name: string;
nameReading: string | null;
website: string | null;
createdAt: firestore.Timestamp | null;
updatedAt: firestore.Timestamp | null;
};
上記で見た目上は縛れる。
ただし何となく突破もできてしまう。
code:main.ts
const db = admin.firestore();
await db.doc('publishers/kodansha').update({ hoge: 'piyo' });
Partial ※1を使って下記で防ぐ
code: main.ts
const diff: Partial<Book> = {};
diff.title = ' 炎炎ノ消防隊(18)';
await db.collection('books').doc('9784065153093').update({
...diff,
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
});
※1 渡された型の全てのプロパティを省略可能に定義し直す、TypeScript の組み込み型関