如何在 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.html.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.

我只是在执行函数时得到一个异常:Functions.GetBlogPosts.mscorlib:ReferenceError:未定义博客帖子.

I simply get a Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined.

我也尝试过明确地require .js 文件,但这似乎没有找到.可能是我走错了路.

I've also tried explitely requireing the .js file, but this seems not to be found. It could be I just got the path wrong.

有人有关于如何在 azure 函数之间共享 .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:

  1. 在根 hosts.json 中添加一行以 watch 共享文件夹.watchDirectories":[共享"]
  2. 在共享文件夹中,添加了一个 blogPostModel.js 文件,其中包含以下架构/模型定义和导出
  1. Add a line to the root hosts.json to watch a shared folder. "watchDirectories": [ "Shared" ]
  2. In the shared folder, added a blogPostModel.js file containing the following schema/model definition and export

sharedlogPostModel.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);

  1. 在我的函数 require 中,共享文件的路径如下:var blogPostModel = require('../Shared/blogPostModel.js');
  1. 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 finds etc in each individual function.

此解决方案由以下 SO 帖子组成:

This solution was composed from the following SO posts:

Node.js 中的 Azure 函数和共享文件

Mongoose 编译后无法覆盖模型

相关文章