Logic Handling

Logic Handling

After defining the Input & Output Types, the next step is to handle the endpoint logic. This is done using the handleLogic method, which accepts a callback function. The callback receives an object of the defined inputType and returns the corresponding outputType. This design leverages TypeScript to provide an enhanced development experience, including type safety, autocompletion, and error prevention, reducing the risk of type-related bugs.

Example

index.ts
import { SchemaValidator, endpoint } from "tarin";
 
// Server initialization
...
 
// Endpoint definition
const searchEndpoint = endpoint.get("/api/search")
  .input({
    query: SchemaValidator.object({
      q: SchemaValidator.string(),
    }),
  })
  .output({
    body: SchemaValidator.object({
      data: SchemaValidator.array({
        id: SchemaValidator.string(),
        title: SchemaValidator.string(),
        description: SchemaValidator.string(),
      }),
      nextId: SchemaValidator.number().optional()
    })
  })
  .handleLogic((input) => {
    // The input type is { query: { q: string; } },
    // providing autocompletion and type checking in IDEs like VSCode.
 
    const books = findBooks(input.query.q);
 
    // Return the expected type: 
    // { body: { data: { id: string; title: string; description: string; }[]; nextId?: number; } }
    return Result.success({ body: { data: books } });
  });
 
tarin.addEndpoints(searchEndpoint);

Key Benefits

  • Automatic Validation: Input and output validation is handled seamlessly behind the scenes. This eliminates the need to write validation logic within the callback, resulting in cleaner and more maintainable code.
  • Type Safety: The use of TypeScript ensures that input and output types are strictly enforced, significantly reducing potential bugs.

Future Enhancements

We are continually improving and will introduce additional features, in future updates.