incubrain / astrotribe

Where astronomers and space-tech enthusiast get their news
https://astronera.org
7 stars 2 forks source link

learning: working with nitro server #78

Open Drew-Macgibbon opened 1 year ago

Drew-Macgibbon commented 1 year ago

I am starting to see similarities with express, but I still need to dig deeper to understand how things work and how I can better structure/optimize the code. This will be a running thread of my findings.

I'm breaking down my findings into separate issue threads, each thread will become an article/video.

  1. h3event: #80
  2. middleware: #81
  3. utils: #82
  4. func - unstorage: #79
Drew-Macgibbon commented 1 year ago

We can use any express package like so:

// middleware/cors.ts
import cors from 'cors';

export default defineEventHandler(({ req, res }) => new Promise((resolve) => cors()(req, res, resolve)));

Or helmet or any express package:

// middleware/helmet.ts
import helmet from 'helmet';

export default defineEventHandler(({ req, res }) => new Promise((resolve) => helmet()(req, res, resolve)));
Drew-Macgibbon commented 1 year ago

Auto-imports

These work the same as client-side auto-imports within your nuxt 3 app.

Example: directory structure.

server/utils/logger.ts
// preference: I like to name files in sub-folders with the folder as a prefix
server/utils/scraper/scraperBlogs.ts

You can now call logger or scraperBlogs directly if they have a default export. Named exports are also directly callable. Let's say the scraperBlogs file has a testFunction named export, yo don't have to prefix it when calling, it can be directly referenced as testFunction()