Skip to content

feat: dynamic data in defineRouteMeta - #3096

Closed
horvbalint wants to merge 4 commits into
nitrojs:v2from
horvbalint:dynamic-defineRouteMeta
Closed

horvbalint wants to merge 4 commits into
nitrojs:v2from
horvbalint:dynamic-defineRouteMeta

Conversation

@horvbalint

@horvbalint horvbalint commented Feb 15, 2025 •

Copy link
Copy Markdown
Contributor

🔗 Linked issue

#2974

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

In this PR I tried to add a very basic implementation of dynamic data in defineRouteMeta. It does not evaluate the meta in build time so if an approach like this is not desired, feel free to close this PR :)

The basic idea is that since we are already creating a virtual file that exports the route meta object for every route, it would make sense to have the computation in these files as well. I am searching through the route file code until the macro invocation is found. Along the way relative imports are updated with their absolute path. If the macro is found, I discard the lines after it and replace it with a default export of its argument.

As an example this route:

import utilityFunction from './utilityPath'
const openAPI = { description: 'The routes description' }

defineRouteMeta({ openAPI })

export default defineEventHandler(() => utilityFunction())

is transformed into this virtual file:

import utilityFunction from 'absolute/path/utilityPath'
const openAPI = { description: 'The routes description' }

export default { openAPI }

Though this is a very simple idea, it is working surprisingly well, allowing us to do very nice things with it like:

import { z } from 'zod'
import { extendZodWithOpenApi, createSchema } from 'zod-openapi'

extendZodWithOpenApi(z)

const bodyValidator = z.object({
    foo: z.enum(["bar", "baz"]).openapi({ description: "Property description" }),
})
const { schema, components } = createSchema(bodyValidator);

defineRouteMeta({
  description: routeDescription,
  requestBody: {
    content: {
      "application/json": {
        schema,
      },
    },
  },
  $global: {
    components,
  },
});

export default defineEventHandler(async (event) => {
  const body = await readValidatedBody(event, validator.parse);
});

The meta or parts of it can also come from imports, so we can create utilities, like:

// server/utils/openapi.ts

import { z } from "zod";
import { extendZodWithOpenApi, createSchema } from "zod-openapi";

extendZodWithOpenApi(z);

export function createValidator<Z extends z.ZodType>(routeDescription: string, callback: (zod: typeof z) => Z) {
  const validator = callback(z);
  const { schema, components } = createSchema(validator);

  return {
    validator,
    openAPI: {
      description: routeDescription,
      requestBody: {
        content: {
          "application/json": {
            schema,
          },
        },
      },
      $global: {
        components,
      },
    },
  };
}
// server/routes/index.post.ts

import { createValidator } from "~/utils/openapi";

const { validator, openAPI } = createValidator("Route description", (z) =>
  z.object({
    foo: z.enum(["bar", "baz"]).openapi({ description: "Property description" }),
  })
);

defineRouteMeta({ openAPI });

export default defineEventHandler(async (event) => {
  const body = await readValidatedBody(event, validator.parse);
});

Of course there is no shortage of drawbacks/todos either:

  • Relative imports can not be used in the macro
  • Every code above the macro runs twice
    • this sounds bad, but users can be encouraged to place the macro as far up in the file as possible. In nuxt they can only appear at the very top
  • If the code above the macro has side-effects, those will happen multiple times
    • I don't think this can be prevented in any way
  • Variables placed under the macro can not be used in it, even if they are usually hoisted (functions, vars)

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

@horvbalint

horvbalint commented Feb 16, 2025 •

Copy link
Copy Markdown
Contributor Author

I had to add acorn as a dependency and use its parse method, because rollup's this.parse had some type mismatches with reality (start and end was not present in it). I am not sure however what the correct parse options would be. Other than that this appeats to be working fine.

@horvbalint
horvbalint marked this pull request as ready for review February 16, 2025 08:42
@horvbalint
horvbalint requested a review from pi0 as a code owner February 16, 2025 08:42
@Navidtm

Navidtm commented Mar 21, 2025

Copy link
Copy Markdown

I'm very excited about this feature 😍.
I hope this feature will be added as soon as possible.

@MahmoodKhalil57

Copy link
Copy Markdown

Hello guys, any updates on this feature? Would love to get my hands on this asap!

@hacxy

hacxy commented Apr 29, 2025

Copy link
Copy Markdown

Hi, Has there been any progress on this feature recently?

@Davvii1

Davvii1 commented May 5, 2025

Copy link
Copy Markdown

Waiting for this feature to be added, this look really cool. Any progress or news on this?

@horvbalint

Copy link
Copy Markdown
Contributor Author

The PR is waiting on a review from Pooya, but it might not be merged at all, since it does not implement the feature in a way that was previously requested by him. I am also rooting for this feature, since I would use it a lot, but please don't leave comments with the intention to speed the process up, cause that will have an opposite effect. Pooya has many many stuff to work on (eg.: upcoming v3 release) and I am sure he will get to this PR once he has the time. If you want to show support, please simply leave a reaction :)

@pi0

pi0 commented May 6, 2025 •

Copy link
Copy Markdown
Member

Thanks for the PR and patience @horvbalint.

We really need to keep supporting build-time evaluation for defineRouteMeta to be able to use it for route rules and any other feature that needs deterministic behavior based on route meta. Also this is important for runtime performance to not be forced to load all route chunks only to see meta.

We might use either jiti or esbuild (or rolldown in the future), which are already deps to bundle (resolve imports, drop all side effects) then eval meta.

Closing PR for clarity (tracker: #2974) if you could make a POC with above in implementations against v3 it is more than welcome ❤️

@pi0 pi0 closed this May 6, 2025
@horvbalint

horvbalint commented May 6, 2025 •

Copy link
Copy Markdown
Contributor Author

@pi0 Thanks for the review. I would love to make this happen at build-time, but I have very little knowledge on how to do that. I suspected that jiti will be the solution and will try to poke around with it, but likely I will need some help on how to structure something like this. Is there a discrod or something where I can ask for some help if needed?

On a sidenote: I know this PR is not exactly what you were looking for, but when setting openAPI.production = 'prerender' this ended up being staticly added to the bundle. Is this not a viable solution? Are middlewares before files in the public dir impossible?

Edit: I seem to forget that defineRouteMeta is not only used for openApi stuff 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants