# Structuring an application

> A simple layout to start from, and two habits worth keeping whatever the layout.

Tetsu reads the routes it is given, not files or folders, so any layout works. Here is a simple one to start from:

```text
src/
  main.ts              starts the server
  app.ts               builds the application
  notes/
    controller.ts      the routes
    service.ts         the logic and the queries
    schemas.ts         what comes in and what goes out
    controller.test.ts
```

Two habits are worth keeping whatever the layout.

## Build the application in a function

`app.ts` makes the services and returns the application:

src/app.ts

```ts
import type { Database } from "bun:sqlite";
import { createApp } from "@tetsujs/core";
import { notesController } from "./notes/controller";
import { NoteService } from "./notes/service";


export function buildApp(db: Database) {
  const notes = new NoteService(db);


  return createApp({ routes: notesController(notes) });
}
```

`main.ts` serves it, and a test builds the same application on a database in memory, so the test runs what the server runs:

src/main.ts

```ts
import { Database } from "bun:sqlite";
import { buildApp } from "./app";


Bun.serve({ ...buildApp(new Database("notes.sqlite")), port: 3000 });
```

src/notes/controller.test.ts

```ts
import { Database } from "bun:sqlite";
import { serve } from "@tetsujs/core/testing";
import { expect, test } from "bun:test";
import { buildApp } from "../app";


const request = serve(buildApp(new Database(":memory:")));


test("lists notes", async () => {
  expect((await request("/notes")).status).toBe(200);
});
```

## Keep HTTP out of services

A service takes values, returns values and throws its own errors; routes and hooks deal with requests. Then a service is tested without a server, and a scheduled job or a script can use it too.

A small runnable application laid out much this way is [`examples/app`](https://github.com/tetsujs/tetsu/tree/main/examples/app).
