brillout / telefunc

Remote Functions. Instead of API.
https://telefunc.com
MIT License
688 stars 31 forks source link

Vite plugin allows custom telefunc context #106

Closed hugo082 closed 7 months ago

hugo082 commented 7 months ago

AFAIK currently the vite plugin doesn't allow to declare a custom middleware and so managing the telefunc context. This is really pain full as it prevent us from using it as soon as authenticated calls are required on the API. https://github.com/brillout/telefunc/blob/a97e22faaf2e30d4f0277394ab6b2030f371014e/telefunc/node/vite/plugins/devConfig.ts#L31-L41 https://github.com/brillout/telefunc/blob/a97e22faaf2e30d4f0277394ab6b2030f371014e/telefunc/node/vite/helpers/addTelefuncMiddleware.ts#L7-L37

It would be great to be able to pass a plugin option to register custom behaviour like:

// vite.config.ts
export default defineConfig({
  plugins: [
    telefunc({
      serverMiddleware: 'src/server.ts'
    })
  ],
  // ...
})
// serc/server.ts
export default async (req, res) => {
  const context = {
    // ...
  }

  const httpResponse = await telefunc({
    url: request.url ?? '/',
    body: request.body,
    method: request.method ?? 'POST',
    context,
  })

  response.setHeader('content-type', httpResponse.contentType)
  response.status(httpResponse.statusCode).send(httpResponse.body)
}

ℹ️ Note that the same behaviour is applied to the preview command here: https://github.com/brillout/telefunc/blob/main/telefunc/node/vite/plugins/previewConfig.ts#L22

brillout commented 7 months ago

You can actually do that, see for example: https://github.com/brillout/telefunc/blob/a97e22faaf2e30d4f0277394ab6b2030f371014e/examples/authentication/server/index.ts#L31

The automatically injected middleware you're referring to isn't really supposed to be used by end-users. (It's only used for creating minimal /examples/.) Admittedly it's confusing and it's something the docs and examples should clarify (it's on the radar).

I guess we can close this, but let me know if you still have questions.

(Btw. in case your company is up for it, we're looking for sponsors.)