如何在JavaScript Azure Functions中共享代码? [英] How to share code in JavaScript Azure Functions?

查看:89
本文介绍了如何在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 requireing 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:

  1. 在根目录hosts.json中添加一行以watch共享文件夹. "watchDirectories": [ "Shared" ]
  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

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

  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函数

一旦编译成猫鼬就无法覆盖模型

这篇关于如何在JavaScript Azure Functions中共享代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆