带有函数框架的云函数
文档:Functions Framework Nodejs
package.json
注意--target 和--signature-type
{
...
"scripts": {
"start": "npx functions-framework --target=helloPubSub --signatur-type=event"
},
"dependencies": {
"@google-cloud/debug-agent": "^7.0.0",
"@google-cloud/storage": "^6.0.0"
},
"devDependencies": {
"@google-cloud/functions-framework": "^3.1.2"
}
...
}
-
downloads file 的示例 nodejs 云函数
/* modified from the sample
index.js
*/
const {Storage} = require('@google-cloud/storage');
function log(message, severity = 'DEBUG', payload) {
// Structured logging
// https://cloud.google.com/functions/docs/monitoring/logging#writing_structured_logs
if (!!payload) {
// If payload is an Error, get the stack trace.
if (payload instanceof Error && !!payload.stack) {
if (!!message ) {
message = message + '\n' + payload.stack;
} else {
message = payload.stack;
}
}
}
const logEntry = {
message: message,
severity: severity,
payload : payload
};
console.log(JSON.stringify(logEntry));
}
function getConfigFile(payload){
console.log("Get Config File from GCS")
const bucketName = 'some-bucket-in-a-project';
const fileName = 'config.json';
// Creates a client
const storage = new Storage();
async function downloadIntoMemory() {
// Downloads the file into a buffer in memory.
const contents = await storage.bucket(bucketName).file(fileName).download();
console.log(
`Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.`
);
}
downloadIntoMemory().catch(console.error);
}
exports.helloPubSub = async (pubSubEvent, context) => {
/*
Read payload from the event and log the exception in App project if the payload cannot be parsed
*/
try {
const payload = Buffer.from(pubSubEvent.body.message.data, 'base64').toString()
const pubSubEventObj = JSON.parse(payload) ;
console.log("name: ", pubSubEventObj.name);
getConfigFile(pubSubEventObj)
} catch (err) {
log('failed to process payload: + payload \n' , 'ERROR', err);
}
};
- Pub/Sub 事件的模拟消息
blog reference,但我没有使用模拟器
myJson.json
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
- Pub/sub 消息的编码 (可能有更好的方法)
cat myJson.json | grep -v % | base64
- 将该输出值转化为数据钥匙:
mockPubSub.json
{
"message": {
"attributes": {
"greeting": "Hello from the Cloud Pub/Sub Emulator!"
},
"data": "< put out base64 from above >",
"messageId": "136969346945"
},
"subscription": "projects/myproject/subscriptions/mysubscription"
}
- 按照从TL;博士:以上。
免责声明
- 在擦洗(即重命名位)并复制它时,我可能搞砸了。对不起,如果这是真的。
- 这都是人为的。如果您对我的设计感到好奇,可以从云调度程序中获取消息,其中包含有关从配置中读取内容的相关详细信息。