Data の追加
Optimistic update を使用して高速かつ応答性の高い user experience を実現します。
Mutations を使用する理由
database 内で新しい record を作成したり、既存の record を更新したりする必要があります。Squid Client SDK は、即時の UI feedback のために client 上で変更を optimistic に適用し、その後 server と非同期に sync する insert および update operation を提供します。
クイックスタート
// Insert a new document
await squid.collection<User>('users').doc('user_1').insert({
name: 'Alice',
email: 'alice@example.com',
});
概要
transaction 内で実行されない限り、すべての insert と update は、mutation が server に適用された時点で resolve する Promise を返します。
insert と update はローカルで optimistic に適用され、client に即時に反映されます。その後、整合性のあるクリーンな data state を確保するため、変更が非同期に server へ送信されます。
write mutation には insert、update、setInPath の 3 種類があります。いずれも document reference に対して実行します。
コアコンセプト
Insert
Insert は新しい document の作成に使用します。
collection に新しい document を insert するには、DocumentReference の insert method を呼び出し、新しい document data を argument として渡します。
try {
await squid.collection<User>('users').doc('new_user_id').insert({
name: 'John Doe',
email: 'johndoe@example.com',
});
console.log('User added successfully');
} catch (error) {
console.error(`Failed to add user ${error}`);
}
backend security rule を使用すると、各 mutation を実行できる user を詳細に制御できます。これらの rule は parameter として MutationContext を受け取ります。これには、変更前後の document snapshot を含む、mutation に必要なすべての detail が含まれます。記述方法については、security rulesを参照してください。
複数の Insert
insertMany method は、複数の document を一度に効率よく insert または update するために使用します。次の例では、新しい user document の array を追加します。
const newDocuments = [
{
id: 'new_user_id1',
data: {
name: 'John Doe',
email: 'johndoe@example.com',
},
},
{
id: 'new_user_id2',
data: {
name: 'Jan Smith',
email: 'jansmith@example.com',
},
},
];
try {
await squid.collection<User>('users').insertMany(newDocuments);
console.log('Users added successfully');
} catch (error) {
console.error(`Failed to add users ${error}`);
}
Update
document を update するには、DocumentReference の update method を呼び出し、partial update data を含む object を argument として渡します。
try {
await squid
.collection<User>('users')
.doc('existing_user_id')
.update({ email: 'new_email@example.com' });
console.log('User updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
Path 内での設定
DocumentReference の setInPath method を呼び出し、property の path と新しい value を argument として渡すことで、document の特定 property を update することもできます。path 内の nested property を指定するには dot notation を使用します。
const userRef = squid.collection<User>('users').doc('existing_user_id');
try {
await userRef.setInPath('address.street', 'Main');
console.log('Updated successfully');
} catch (error) {
console.error(`Failed to update user ${error}`);
}
Error Handling
| Error | 原因 | 解決策 |
|---|---|---|
| Security rule rejection | mutation が security rules によって block された | user が collection への write permission を持つことを確認する |
| Document already exists | 一部の connector type で、すでに存在する document ID に対して insert を呼び出した | 既存 document には update を使用するか、一意の ID を使用する |
| Invalid data shape | insert する data が collection schema と一致しない | data object が期待される schema と type に一致することを確認する |
| Network error | mutation を確認するために server へ到達できなかった | optimistic update は rollback されます。operation を retry してください |
ベストプラクティス
-
partial change には
update()を使用します。 document 全体を再 insert するのではなく、変更された field だけを送信します。 -
深く nested した update には
setInPath()を使用します。 document の残りの部分に触れることなく、単一の nested field を変更できます。Client code// Update only the city without affecting other address fields
await userRef.setInPath('address.city', 'New York'); -
bulk operation には
insertMany()を使用します。 server への round trip 数を削減できます。 -
複数 document にわたる atomicity が必要な場合は、関連する mutation を transaction でラップします。
-
client-side validation を通過しても、security rule または schema check に失敗して server が変更を拒否する場合があるため、mutation の error を処理します。