Skip to content

Instantly share code, notes, and snippets.

@jchris
Last active February 25, 2025 23:42
Show Gist options
  • Save jchris/5a3f56914b23d278c53f8d4417bc067f to your computer and use it in GitHub Desktop.
Save jchris/5a3f56914b23d278c53f8d4417bc067f to your computer and use it in GitHub Desktop.
quick and dirty mock
const mockUseFireproof = (dbName) => {
const [state, setState] = React.useState({
database: null,
docs: []
});
// Initialize database if not already done
React.useEffect(() => {
if (!state.database) {
setState(s => ({
...s,
database: {
// Create or update a document
put: (doc) => {
const docWithId = { ...doc, _id: doc._id || `doc_${Date.now()}` };
setState(s => ({
...s,
docs: s.docs.some(d => d._id === docWithId._id)
? s.docs.map(d => d._id === docWithId._id ? docWithId : d)
: [...s.docs, docWithId]
}));
return Promise.resolve({ ok: true, id: docWithId._id });
},
// Get a document by ID
get: (id) => {
const doc = state.docs.find(d => d._id === id);
if (doc) {
return Promise.resolve(doc);
} else {
return Promise.reject(new Error(`Document with id ${id} not found`));
}
},
// Delete a document
del: (idOrDoc) => {
const id = typeof idOrDoc === 'string' ? idOrDoc : idOrDoc._id;
const docExists = state.docs.some(d => d._id === id);
if (docExists) {
setState(s => ({
...s,
docs: s.docs.filter(d => d._id !== id)
}));
return Promise.resolve({ ok: true, id });
} else {
return Promise.reject(new Error(`Document with id ${id} not found`));
}
}
}
}));
}
}, []);
return {
database: state.database,
useDocument: (initialDoc = {}) => {
const [doc, setDoc] = React.useState(initialDoc);
return {
doc,
merge: (update) => setDoc(current => ({ ...current, ...update })),
submit: () => {
if (state.database) {
return state.database.put(doc);
}
return Promise.reject(new Error("Database not initialized"));
}
};
},
useLiveQuery: (field, options = {}) => {
const { docs } = state;
// Basic filtering functionality
let filteredDocs = [...docs];
if (typeof field === 'string' && options.key) {
filteredDocs = filteredDocs.filter(doc => doc[field] === options.key);
} else if (typeof field === 'string' && options.descending !== undefined) {
filteredDocs.sort((a, b) => {
return options.descending
? (b[field] || '').toString().localeCompare((a[field] || '').toString())
: (a[field] || '').toString().localeCompare((b[field] || '').toString());
});
} else if (typeof field === 'function') {
// Handle function mapper with prefixes
if (options.prefix && Array.isArray(options.prefix)) {
filteredDocs = filteredDocs.filter(doc => {
const fieldValues = field(doc);
return options.prefix.every((prefix, i) =>
fieldValues[i] && fieldValues[i].toString().startsWith(prefix)
);
});
}
}
// Handle limit
if (options.limit && typeof options.limit === 'number') {
filteredDocs = filteredDocs.slice(0, options.limit);
}
return { docs: filteredDocs };
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment