elysia icon indicating copy to clipboard operation
elysia copied to clipboard

feature: maybe add .use(...plugins)

Open PandaWorker opened this issue 1 year ago • 1 comments
trafficstars

What is the problem this feature would solve?

Simplifies the code

What is the feature you are proposing to solve the problem?

import { Elysia, error } from 'elysia';
import { randomUUID } from 'node:crypto';

// plugin1
const plugin1 = new Elysia().derive(({ headers, set }) => {
	const requestId = headers['x-request-id'] ?? randomUUID();

	set.headers['x-request-id'] = requestId;

	return {
		requestId: requestId,
	};
});

// plugin2
const roles = ['owner', 'admin', 'user'] as const;
type Role = (typeof roles)[number];

const plugin2 = new Elysia({ name: 'roles' }).macro(({ onBeforeHandle }) => {
	return {
		role: (allowed: Role) => {
			onBeforeHandle({ insert: 'after' }, ({ headers }) => {
				if (headers['x-user-role'] !== allowed) {
					return error('Forbidden', {
						code: 'access',
						message: 'Доступ запрещен',
					});
				}
			});
		},
	};
});

// plugin3
const plugin3 = new Elysia().decorate('getDate', () => Date.now());

export default new Elysia({ prefix: '/users', name: 'users.module' })
	// more .use(plugin)
	.use(plugin1)
	.use(plugin2)
	.use(plugin3)

	.onBeforeHandle(({ headers }) => {
		headers['x-user-role'] = 'admin';
	})
	.post(
		'/',
		({ getDate, requestId, headers}) => {

			return {
				date: getDate(),
			};
		},
		{ role: 'admin' }
	);

    // or .use(...plugins)
    // .use(
    //     plugin1,
    //     plugin2,
    //     plugin3
    // )

What alternatives have you considered?

No response

PandaWorker avatar Feb 18 '24 11:02 PandaWorker

@SaltyAom

Can I take on this issue?

I plan to add support for array in the current use function. The existing code has support for it but the type is missing, only allow for use with single plugin only. I am going with use(plugins: MaybeArray<...>) since rest parameter wont work with the overload that has options as the last parameter.

HigherOrderLogic avatar Sep 07 '24 07:09 HigherOrderLogic