Create grouped cloud functions automagically from an appropriately named file structure, while retaining the ability to selectively deploy to the cloud.
Take the following structure as an example:
functions
-node_modules
-utils
-endpoints
-user
-create.js
-update.js
-friend
-add.js
-remove.js
-admin
-list.js
-debug
-user.js
-ignore
-system.js
It would create this export structure:
exports = {
user: {
create(),
update(),
friend: { add(), remove() }
admin: { list() }
}
debug: { user() }
}
Serve these functions locally:
✔ functions: user.create: http://localhost:5000/{project}/{region}/user-create
✔ functions: user.update: http://localhost:5000/{project}/{region}/user-update
✔ functions: user.friend.add: http://localhost:5000/{project}/{region}/user-friend-add
✔ functions: user.friend.remove: http://localhost:5000/{project}/{region}/user-friend-remove
✔ functions: user.admin.list: http://localhost:5000/{project}/{region}/user-admin-list
✔ functions: debug.user: http://localhost:5000/{project}/{region}/debug-user
And deploy these functions to the server:
✔ Function URL (user-create): https://{region}-{project}.cloudfunctions.net/user-create
✔ Function URL (user-update): https://{region}-{project}.cloudfunctions.net/user-update
✔ Function URL (user-friend-add): https://{region}-{project}.cloudfunctions.net/user-friend-add
✔ Function URL (user-friend-remove): https://{region}-{project}.cloudfunctions.net/user-friend-remove
The following structure would do the same thing (dots.not.dirs):
functions
-node_modules
-utils
-endpoints
-user.create.js
-user.update.js
-user.friend.add.js
-user.friend.remove.js
-user.admin.list.js
-debug.user.js
-debug.ignore.system.js
I prefer the second dot-notation approach as it makes require('./../utils')
easier than nesting.
Note the available naming modifiers which can appear in any part of the path; either as a directory name, or separated by dot notation anywhere in a file name:
Modifier | shorthand | description |
---|---|---|
admin | a | admin functions do not deploy and are only available when emulating locally |
debug | d | debug functions do not deploy and are only available when emulating locally |
ignore | i | ignored scripts can sit within the folder structure without being parsed |
Finally if you were to selectively firebase deploy --only function:users.friend
you would get:
✔ Function URL (user-friend-add): https://{region}-{project}.cloudfunctions.net/user-friend-add
✔ Function URL (user-friend-remove): https://{region}-{project}.cloudfunctions.net/user-friend-remove
P.S. the script may require Node 10+ to run as-is. To target the correct runtime update the engines
field in your package.json
:
"engines": {"node": "10"}
If you have deploy error like below. I think
index.js
to uses some unsupported api which is stable node version 8 on functions.Change this in your package.json
Reference:
https://firebase.google.com/docs/functions/manage-functions?#set_runtime_options