前提
FirebaseのCloud FunctionsでBufferを返したい下記の関数があります。
TypeScript
1exports.getBuffer = functions 2 .runWith({ 3 timeoutSeconds: 10, 4 }) 5 .https.onCall((aug, context) => { 6 7 let chunks = []; 8 const stream = getExampleStream(aug); 9 10 stream.on("data", (data) => { 11 chunks.push(data); 12 }); 13 stream.on("error", (err) => { 14 console.log(err); 15 }); 16 stream.on("end", () => { 17 const buf = Buffer.concat(chunks); 18 }); 19};
実現したいこと
前述の"end"の関数でbuf
が生成されたらgetBuffer
関数を終了し、getBuffer
関数の呼び出し元にbuf
を返したいです。
試したこと・発生している問題
「Aが終わったら、Bを実行する」という処理を実現するためにネットで検索したところ、Promiseを使うとよい、という主旨をいくつかの記事で読み取りました。
そこで下記のように書いてみました。
Typescript
1const promise = new Promise((resolve, reject) => { 2 stream.on("data", (data) => { 3 chunks.push(data); 4 }); 5 stream.on("error", (err) => { 6 console.log(err); 7 reject(err); 8 }); 9 stream.on("end", () => { 10 const buf = Buffer.concat(chunks); 11 resolve(buf); 12 }); 13}; 14return promise.then(buf => { 15 return buf; 16}).catch(err => { 17 return err; 18});
上記は書き方が悪かったのか、タイムアウトします。
上記のgetBuffer関数はonRequestの形式であれば機能しました。
Typescript
1 stream.on("data", (data) => { 2 chunks.push(data); 3 }); 4 stream.on("error", (err) => { 5 console.log(err); 6 res.status(400).json({err}); 7 }); 8 stream.on("end", () => { 9 res.write(buffer); 10 res.status(200).end(); 11 });
しかし、onRequestの形式だとAppCheckの対応が難しそうだったので、onCallの形式にしようとしています。
あなたの回答
tips
プレビュー