如何在JavaScript Azure Functions中共享代码? [英] How to share code in JavaScript Azure Functions?
问题描述
如何在Azure函数应用中的文件之间共享代码(例如Mongo架构定义)?
How can I share code (e.g. Mongo schema definitions) between files in an Azure function app?
我需要这样做,因为我的函数需要访问共享的mongo模式和模型,例如以下基本示例:
I need to do this, as my functions require access to a shared mongo schema and models, such as this basic example:
var blogPostSchema = new mongoose.Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
var BlogPost = mongoose.model('BlogPost', blogPostSchema);
我尝试在host.json
中添加"watchDirectories": [ "Shared" ]
行,并在该文件夹中添加了包含上述变量定义的index.js
,但这似乎不适用于其他功能.
I've tried to add a "watchDirectories": [ "Shared" ]
line to my host.json
and in that folder added an index.js
containing the above variable definition but this doesn't seem to be available to the other functions.
我只是得到一个Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined
.
我还尝试了require
.js文件,但是似乎找不到.可能是我走错了路.
I've also tried explitely require
ing the .js file, but this seems not to be found. It could be I just got the path wrong.
有人在蓝色函数之间共享.js
代码的示例或提示吗?
Does anyone have an example or tips on how to share .js
code between azure functions?
推荐答案
我通过执行以下步骤解决了此问题:
I fixed this issue by doing the following steps:
- 在根目录
hosts.json
中添加一行以watch
共享文件夹."watchDirectories": [ "Shared" ]
- 在共享文件夹中,添加了一个包含以下架构/模型定义的
blogPostModel.js
文件并导出
- Add a line to the root
hosts.json
towatch
a shared folder."watchDirectories": [ "Shared" ]
- In the shared folder, added a
blogPostModel.js
file containing the following schema/model definition and export
shared \ blogPostModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogPostSchema = new Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
module.exports = mongoose.model('BlogPost', blogPostSchema);
- 在我的函数
require
中,共享文件具有以下路径:var blogPostModel = require('../Shared/blogPostModel.js');
- In my function
require
the shared file with the following path:var blogPostModel = require('../Shared/blogPostModel.js');
然后我可以建立连接并在每个单独的函数中执行find
等与模型交互.
I can then make a connection and interact with the model doing find
s etc in each individual function.
此解决方案由以下SO帖子组成:
This solution was composed from the following SO posts:
这篇关于如何在JavaScript Azure Functions中共享代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!