Skip to content

Instantly share code, notes, and snippets.

@pi0

pi0/nuxt-functins.md

Last active Apr 3, 2020
Embed
What would you like to do?

Nuxt functions implementation specs

Initial RFC: https://github.com/nuxt/rfcs/issues/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.

Usage

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.

Components

FunctionsContainer

Manages function providers and keeps function meta. Modules can actually use instance of this class to register their functions.

DirectoryProvider (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)

FunctionsSandbox

Provides runtime for both development and production for running functions (nuxt dev and nuxt start). Serverless target does not requires sandbox anymore.

Functions Builder

Using an integrated webpack config to efficiently build provided functions based on their meta.

Runtime Integration ($functions)

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.

FunctionsMeta

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

Services

    import useDB from '@nuxtjs/db'
    
    export default async function () {
      // do validation
    
      const db = await useDB()
      const post = db.getPost()
    	return { post }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment