Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Simple API Example

A complete working REST API with CRUD operations, validation, and error handling. Copy and customize.

Complete Working Example

1import { createApp } from '@morojs/moro';
2import { z } from 'zod';
3
4const app = createApp();
5
6// User schema for validation
7const UserSchema = z.object({
8  name: z.string().min(1),
9  email: z.string().email(),
10  age: z.number().min(18).optional()
11});
12
13// In-memory store (replace with database in production)
14const users: z.infer<typeof UserSchema>[] = [];
15let nextId = 1;
16
17// GET /users - List all users
18app.get('/users', () => {
19  return { success: true, data: users };
20});
21
22// GET /users/:id - Get user by ID
23app.get('/users/:id', ({ params }) => {
24  const user = users.find(u => u.id === parseInt(params.id));
25  if (!user) {
26    return { success: false, error: 'User not found' };
27  }
28  return { success: true, data: user };
29});
30
31// POST /users - Create new user
32app.post('/users', {
33  body: UserSchema,
34  handler: ({ body }) => {
35    const newUser = {
36      id: nextId++,
37      ...body
38    };
39    users.push(newUser);
40    return { success: true, data: newUser };
41  }
42});
43
44// PUT /users/:id - Update user
45app.put('/users/:id', {
46  body: UserSchema.partial(),
47  handler: ({ params, body }) => {
48    const userIndex = users.findIndex(u => u.id === parseInt(params.id));
49    if (userIndex === -1) {
50      return { success: false, error: 'User not found' };
51    }
52    users[userIndex] = { ...users[userIndex], ...body };
53    return { success: true, data: users[userIndex] };
54  }
55});
56
57// DELETE /users/:id - Delete user
58app.delete('/users/:id', ({ params }) => {
59  const userIndex = users.findIndex(u => u.id === parseInt(params.id));
60  if (userIndex === -1) {
61    return { success: false, error: 'User not found' };
62  }
63  users.splice(userIndex, 1);
64  return { success: true, message: 'User deleted' };
65});
66
67app.listen(3000, () => {
68  console.log('API running on http://localhost:3000');
69});

What This Does

  • Creates a complete REST API with CRUD operations
  • Uses Zod for validation and automatic type inference
  • Implements standardized response patterns with success boolean
  • Type-safe throughout - TypeScript knows what's available

Key Features Highlighted

Type-Safe Validation

1const UserSchema = z.object({
2  name: z.string().min(1),
3  email: z.string().email()
4});
5
6// TypeScript automatically knows the type!
7app.post('/users', {
8  body: UserSchema,
9  handler: ({ body }) => {
10    // body.name: string
11    // body.email: string
12    // TypeScript autocomplete works!
13    return { success: true, data: body };
14  }
15});

Standardized Responses

1// Success response
2return { success: true, data: user };
3
4// Error response
5return { success: false, error: 'User not found' };
6
7// Frontend can use discriminated unions
8if (result.success) {
9  // TypeScript knows result.data exists
10} else {
11  // TypeScript knows result.error exists
12}

Try It Yourself

Copy the code above, save it as server.ts, and run:

1npm install @morojs/moro zod
2npx tsx server.ts

Test the API

GET http://localhost:3000/users
POST http://localhost:3000/users
GET http://localhost:3000/users/1

Next Steps