Skip to content

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

Open
@PandaWorker

Description

@PandaWorker

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions