Svelte Firekit: Firestore/Doc Mutation
Document Mutations
Firestore document mutations with automatic timestamps and error handling.
Overview
FirekitDocumentMutations provides methods for creating, reading, updating, and deleting Firestore documents with built-in timestamp management and error handling.
Features
- CRUD operations for Firestore documents
- Automatic timestamp management
- Built-in error handling
- Type-safe operations
- Document existence checking
- Custom ID support
- Merge options for updates
Basic Usage
import { firekitDocMutations } from 'svelte-firekit';
// Add a new document
const result = await firekitDocMutations.add('users', {
name: 'John Doe',
email: '[email protected]'
});
// Set a document
await firekitDocMutations.set('users/123', {
name: 'John Doe',
email: '[email protected]'
});
// Update a document
await firekitDocMutations.update('users/123', {
name: 'Jane Doe'
});
// Delete a document
await firekitDocMutations.delete('users/123');
API Reference
Interfaces
interface MutationResponse<T> {
success: boolean;
data?: T;
id?: string;
error?: {
code: string;
message: string;
};
}
interface MutationOptions {
timestamps?: boolean; // Enable/disable automatic timestamps
merge?: boolean; // Merge or overwrite on set operations
customId?: string; // Custom document ID for add operations
}
Methods
add
Adds a new document to a collection.
async add<T>(
collectionPath: string,
data: WithFieldValue<T>,
options?: MutationOptions
): Promise<MutationResponse<T>>
set
Sets a document’s data.
async set<T>(
path: string,
data: WithFieldValue<T>,
options?: MutationOptions
): Promise<MutationResponse<T>>
update
Updates specific fields in a document.
async update<T>(
path: string,
data: PartialWithFieldValue<T>,
options?: MutationOptions
): Promise<MutationResponse<Partial<T>>>
delete
Deletes a document.
async delete(
path: string
): Promise<MutationResponse<void>>
exists
Checks if a document exists.
async exists(
path: string
): Promise<boolean>
getDoc
Retrieves a document.
async getDoc<T>(
path: string
): Promise<MutationResponse<T>>
Examples
Adding Documents
interface User {
id: string;
name: string;
email: string;
}
// Add with auto-generated ID
const result = await firekitDocMutations.add<User>('users', {
name: 'John Doe',
email: '[email protected]'
});
// Add with custom ID
const resultWithId = await firekitDocMutations.add<User>('users', {
name: 'Jane Doe',
email: '[email protected]'
}, {
customId: 'jane123'
});
Setting Documents
// Set with merge
const setResult = await firekitDocMutations.set<User>('users/123', {
name: 'John Updated'
}, {
merge: true,
timestamps: true
});
// Set without merge (overwrites)
await firekitDocMutations.set<User>('users/123', {
name: 'John Doe',
email: '[email protected]'
});
Updating Documents
// Partial update
const updateResult = await firekitDocMutations.update<User>('users/123', {
name: 'John Updated'
});
// Update with timestamps disabled
await firekitDocMutations.update<User>('users/123', {
name: 'John Updated'
}, {
timestamps: false
});
Error Handling
const result = await firekitDocMutations.add<User>('users', {
name: 'John Doe',
email: '[email protected]'
});
if (!result.success) {
console.error(
`Error: ${result.error?.code} - ${result.error?.message}`
);
} else {
console.log('Document added:', result.data);
}
Automatic Timestamps
Documents are automatically timestamped with:
createdAt
andcreatedBy
on creationupdatedAt
andupdatedBy
on all mutations
// Timestamps are added automatically
const doc = await firekitDocMutations.add('users', {
name: 'John'
});
// Results in:
// {
// name: 'John',
// createdAt: <ServerTimestamp>,
// createdBy: <UserID>,
// updatedAt: <ServerTimestamp>,
// updatedBy: <UserID>
// }
Best Practices
Type Safety
interface User { id: string; name: string; email: string; } // Use the interface with mutations const user = await firekitDocMutations.add<User>('users', { name: 'John', email: '[email protected]' });
Error Handling
const result = await firekitDocMutations.set<User>('users/123', data); if (!result.success) { // Handle error console.error(result.error?.message); return; } // Use the data const userData = result.data;
Document Existence
// Check before operations if (await firekitDocMutations.exists('users/123')) { await firekitDocMutations.update('users/123', data); }
Technical Details
- All operations are performed on the Firestore instance
- Document IDs are automatically included in the data
- Timestamps use Firestore’s serverTimestamp()
- Error responses include both code and message
On this page
Need help with your project?
I offer custom development services, consulting, and technical guidance for your web applications.
Let's work together