Initial RFC: nuxt/rfcs#35
This is a Draft
Introducing a functions/
directory could have a powerful effect for users that want to add server functions but without having to go through serverMiddleware
Functions can be also provided by Nuxt modules, for example, CMS module or auth provider can add it's functionalities to the user context.
functions/blog/getArticle.js
export default async function (payload) {
return { title: 'Hello world' }
})
Nuxt will build this function and make it available both as a HTTP endpoint and SSR service. Functions are lazy loaded by first call.
On the app side, it will expose a $functions
service:
pages/blog.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
export default {
async asyncData ({ $functions }) {
const { title } = await $functions.blog.getArticle()
return { title }
}
}
</script>
One big advantage of this combined with functions meta, is DX that we can generate types as well.
Manages function providers and keeps function meta. Modules can actually use instance of this class to register their functions.
Automatically scans a directory to load functions and assign path, namespace and function name based on directory structure (*path can be customized by function exports)
Provides runtime for both development and production for running functions (nuxt dev
and nuxt start
). Serverless target does not requires sandbox anymore.
Using an integrated webpack config to efficiently build provided functions based on their meta.
A nuxt plugin is required to make function calls. It is different for server and client as for client, we need to make HTTP calls * and for server direct function calls.
All components including builder and runtime need to access this meta-data which is stored as an arrayin functions container. The meta includes:
- Function id (example.namespace.functionName)
- Function type (Currently only
FILE
supported) - Other props including validators
import useDB from '@nuxtjs/db'
export default async function () {
// do validation
const db = await useDB()
const post = db.getPost()
return { post }
}