How can I share code (e.g. Mongo schema definitions) between files in an Azure function app?
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);
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.
I simply get a Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined
.
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.
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
towatch
a shared folder."watchDirectories": [ "Shared" ]
blogPostModel.js
file containing the following schema/model definition and exportshared\blogPostModel.js
require
the shared file with the following path:var blogPostModel = require('../Shared/blogPostModel.js');
I can then make a connection and interact with the model doing
find
s etc in each individual function.This solution was composed from the following SO posts:
Azure Function in Node.js and shared files
Cannot overwrite model once compiled Mongoose