Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improving developer experience for Fastify + Envalid users #1

Open
simenandre opened this issue Apr 4, 2023 · 1 comment
Open

Improving developer experience for Fastify + Envalid users #1

simenandre opened this issue Apr 4, 2023 · 1 comment

Comments

@simenandre
Copy link

Hello 👋

Thank you for this library!

I have a few suggestions to make this a helpful library for more users. The way we use envalid along Fastify is where we decorate a variable called config (or similar) with the result of cleanEnv. This produces a easy way to get configuration value. Typically we have one configuration file (config.ts). It looks something like this:

import { cleanEnv, str } from 'envalid';

// In reality, we also add a custom middleware here 👇
export const config = cleanEnv(process.env, {
	HELLO_WORLD: str({ devDefault: 'something' }),
});

export type Config = typeof config;

Along with this, we add the Config type to a global type definition file as such:

import { Config } from './config.js';

declare module 'fastify' {
  interface FastifyRequest {
    config: Config;
  }
}

And lastly, in our server.ts file, you'll typically see:

// ...
server.decorateRequest('config', config);
// ...

I haven't tried, but I think we can wrap some (or all) of this in a Fastify plugin for a better developer experience. I imagine something like this:

In our config.ts file:

import { fastifyEnv } from 'fastify-envalid';
import { str } from 'envalid';

export const config = fastifyEnv({
	HELLO_WORLD: str({ devDefault: 'something' }),
});

I imagine fastifyEnv (or another name) could come prebuilt with custom middleware and wired with environment variables (potentially changed with the fastify.register function).

Moving on to the server.ts file:

import { fastifyEnvalid } from 'fastify-envalid';
import { config } from './config.js';

// ...
server.register(fastifyEnvalid, { config });
// ...

I think we can wire the types somehow here so they're available just by registering the plugin. Not sure, I haven't played around with it yet. Regardless, what do you think?

@simenandre simenandre changed the title Refactor suggestion Improving developer experience for Fastify + Envalid users Apr 4, 2023
@simenandre
Copy link
Author

simenandre commented Apr 4, 2023

Not to mention that the plugin can easily fix this: af/envalid#141

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

No branches or pull requests

1 participant