I am implementing a command/response pattern where the user writes to a command collection by calling `add` with a payload under his own userId, and then gets the data from a similar response path.
However the code below doesn't work, because onSnapshot can not listen for a document that hasn't yet been created. This would be easy to solve with an onCreate handler, which does exist for cloud functions.
export async function register(fs: any, userId: string) {
try {
// issue a new command
const command = await fs.add(
{ collection: `commands/${userId}/register` },
{ payload: fs.firestore.FieldValue.serverTimestamp() }
);
// wait for the response to be written
fs.onSnapshot(
{ collection: `responses/${userId}/register`, doc: command.id },
function onNext(doc) {
// an error might have occurred at application level
const err = doc.get('error');
if (err) {
return notify.error({ title: 'Failed to register', message: err.message });
}
const payload = doc.get('payload');
notify.json(payload);
},
function onError(err) {
notify.error(err);
}
);
} catch (err) {
notify.error(err);
}
}
Why is there no such thing?
The only scalable solution I can think of is to store the response data as a child in the command document. But I'm wondering if I'm not overlooking some API...