O que é Elysia
Elysia é um framework web de alta velocidade otimizado para o runtime Bun. Suas características incluem End-to-End type safety, API ergonômica e performance impressionante.
Performance
Benchmark (requisições/segundo):
- Express (Node.js): 15.000
- Fastify (Node.js): 45.000
- Hono (Bun): 120.000
- Elysia (Bun): 150.000+
Uso Básico
import { Elysia } from 'elysia';
const app = new Elysia()
.get('/', () => 'Hello, Elysia!')
.get('/user/:id', ({ params: { id } }) => `User ${id}`)
.post('/users', ({ body }) => body)
.listen(3000);
console.log(`🦊 Server running at ${app.server?.url}`);
Type Safety
Inferência Automática de Tipos
import { Elysia, t } from 'elysia';
const app = new Elysia()
.post('/users', ({ body }) => {
// body é automaticamente tipado
return { id: 1, ...body };
}, {
body: t.Object({
name: t.String(),
email: t.String({ format: 'email' }),
age: t.Optional(t.Number())
}),
response: t.Object({
id: t.Number(),
name: t.String(),
email: t.String(),
age: t.Optional(t.Number())
})
});
Cliente End-to-End Type Safe
// server.ts
import { Elysia, t } from 'elysia';
export const app = new Elysia()
.get('/users', () => [{ id: 1, name: 'Alice' }])
.get('/users/:id', ({ params }) => ({ id: params.id, name: 'Alice' }))
.post('/users', ({ body }) => ({ id: 1, ...body }), {
body: t.Object({ name: t.String() })
});
export type App = typeof app;
// client.ts
import { treaty } from '@elysiajs/eden';
import type { App } from './server';
const client = treaty<App>('http://localhost:3000');
// Inferência de tipos completa
const users = await client.users.get();
const user = await client.users({ id: '1' }).get();
const newUser = await client.users.post({ name: 'Bob' });
Sistema de Plugins
Plugins Integrados
import { Elysia } from 'elysia';
import { swagger } from '@elysiajs/swagger';
import { cors } from '@elysiajs/cors';
import { jwt } from '@elysiajs/jwt';
const app = new Elysia()
.use(swagger())
.use(cors())
.use(jwt({
name: 'jwt',
secret: process.env.JWT_SECRET!
}))
.get('/protected', async ({ jwt, cookie: { auth } }) => {
const profile = await jwt.verify(auth.value);
if (!profile) throw new Error('Unauthorized');
return profile;
});
Plugin Customizado
import { Elysia } from 'elysia';
const myPlugin = new Elysia({ name: 'my-plugin' })
.decorate('myService', {
greet: (name: string) => `Hello, ${name}!`
})
.derive(({ headers }) => ({
userId: headers['x-user-id']
}));
const app = new Elysia()
.use(myPlugin)
.get('/', ({ myService, userId }) => {
return myService.greet(userId ?? 'Guest');
});
Ciclo de Vida
const app = new Elysia()
// Antes da requisição
.onBeforeHandle(({ request }) => {
console.log(`${request.method} ${request.url}`);
})
// Após a resposta
.onAfterHandle(({ response }) => {
console.log('Response sent');
})
// Tratamento de erros
.onError(({ error, code }) => {
console.error(`Error: ${code}`, error);
return { error: error.message };
})
.get('/', () => 'Hello');
Grupos e Guards
const app = new Elysia()
.group('/api', (app) =>
app
.guard({
beforeHandle: ({ headers }) => {
if (!headers['authorization']) {
throw new Error('Unauthorized');
}
}
})
.get('/users', () => [])
.get('/posts', () => [])
)
.listen(3000);
Streaming
import { Elysia } from 'elysia';
const app = new Elysia()
.get('/stream', function* () {
yield 'Hello ';
yield 'World ';
yield '!';
})
.get('/sse', ({ set }) => {
set.headers['content-type'] = 'text/event-stream';
return new ReadableStream({
start(controller) {
let count = 0;
const interval = setInterval(() => {
controller.enqueue(`data: ${count++}\n\n`);
if (count >= 10) {
clearInterval(interval);
controller.close();
}
}, 1000);
}
});
});
WebSocket
import { Elysia } from 'elysia';
const app = new Elysia()
.ws('/ws', {
message(ws, message) {
ws.send(`Echo: ${message}`);
},
open(ws) {
console.log('Connection opened');
},
close(ws) {
console.log('Connection closed');
}
});
Geração Automática de Swagger
import { Elysia, t } from 'elysia';
import { swagger } from '@elysiajs/swagger';
const app = new Elysia()
.use(swagger({
documentation: {
info: { title: 'My API', version: '1.0.0' }
}
}))
.get('/users', () => [], {
response: t.Array(t.Object({
id: t.Number(),
name: t.String()
})),
detail: {
summary: 'Get all users',
tags: ['users']
}
});
// Documentação disponível em http://localhost:3000/swagger
Conclusão
Elysia é um framework web de alta velocidade que maximiza o desempenho do Bun. Com End-to-End type safety e API ergonômica, é possível construir aplicações full-stack type-safe de forma eficiente.
← Voltar para a lista