如何在 JavaScript Azure Functions 中共享代码?
How to share code in JavaScript Azure Functions?
如何在 Azure 函数应用程序的文件之间共享代码(例如 Mongo 架构定义)?
我需要这样做,因为我的函数需要访问共享的 mongo 架构和模型,例如这个基本示例:
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
但这似乎不可用到其他功能。
我只是得到一个Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined
。
我也试过明确地 require
ing .js 文件,但这似乎找不到。可能是我走错路了
有人有关于如何在 Azure 函数之间共享 .js
代码的示例或提示吗?
我通过执行以下步骤解决了这个问题:
- 添加一行到根
hosts.json
到 watch
共享文件夹。 "watchDirectories": [ "Shared" ]
- 在共享文件夹中,添加了一个
blogPostModel.js
文件,其中包含以下schema/model定义和导出
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');
然后我可以建立连接并与模型进行交互,在每个单独的函数中执行 find
s 等。
此解决方案由以下 SO 帖子组成:
Cannot overwrite model once compiled Mongoose
如何在 Azure 函数应用程序的文件之间共享代码(例如 Mongo 架构定义)?
我需要这样做,因为我的函数需要访问共享的 mongo 架构和模型,例如这个基本示例:
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
但这似乎不可用到其他功能。
我只是得到一个Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined
。
我也试过明确地 require
ing .js 文件,但这似乎找不到。可能是我走错路了
有人有关于如何在 Azure 函数之间共享 .js
代码的示例或提示吗?
我通过执行以下步骤解决了这个问题:
- 添加一行到根
hosts.json
到watch
共享文件夹。"watchDirectories": [ "Shared" ]
- 在共享文件夹中,添加了一个
blogPostModel.js
文件,其中包含以下schema/model定义和导出
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');
然后我可以建立连接并与模型进行交互,在每个单独的函数中执行 find
s 等。
此解决方案由以下 SO 帖子组成:
Cannot overwrite model once compiled Mongoose