Notes
Notes is a small web app. You write a note in a form, and the app saves it in a SQLite database. The home page lists every note. The app also has a small JSON API for the same notes.
The app shows how the parts of a Novis project work together:
- HTML pages built with
htmltemplates, which escape every value. - A SQLite database, opened with
Core\Db::connect. - Routes, written as attributes on the methods that handle them.
- A form that is checked before anything is saved.
- Tests that send requests to the app without a server.
The code
Section titled “The code”Each tab shows one file of the app. These are the same files that you download below.
# The server listens on port 8142. The other apps in this repository use other ports,# so all of them can run at the same time.[server]listen = ["127.0.0.1:8142"]
# The notes are kept in the SQLite file `notes.sqlite`, next to this file.# Novis creates the file when the first request opens the database.[db.notes]driver = "sqlite"path = "notes.sqlite"
# The tests use this database. It is kept in memory and deleted when the tests end.[db.scratch]driver = "sqlite"path = ":memory:"
# The program may open these two databases and no other.[capabilities.db]connect = ["notes", "scratch"]<?nvs// This is the entry file. `nvs serve public/index.nvs` runs it once for each request.// The `autoload` line reads each class `Notes\...` from the folder `src`.autoload 'Notes' from '../src';
// `dispatch` finds the route for the request and calls its method.// `Notes\Gate` decides if the method may run, and it shows the error pages.Core\Router::dispatch(new Notes\Gate());<?nvsnamespace Notes;
use Core\Access;use Core\Audience;use Core\Db;use Core\Http\Method;use Core\Request;use Core\Response;use Core\Route;use ParseError;
// The routes of the app. Each method with a `Route` handles one kind of request.// `Core\Router::dispatch` in `public/index.nvs` calls the method of the route that matches.final class App{ // Shows the form and every note. #[Route(path: '/', method: Method::Get)] #[Access(allow: Audience::Public)] public static function home(): void { Response::sendHtml(Pages::home(App::store()->all(), new Draft('', ''), [])); }
// Saves the note from the form. If the form is not valid, it shows the form again with the problems. #[Route(path: '/notes', method: Method::Post)] #[Access(allow: Audience::Public)] public static function save(): void { var $store = App::store(); Draft $draft = new Draft('', ''); array<string> $problems = []; try { // `postAs` fills a `Draft` from the form fields `title` and `body`. $draft = Request::formFieldsAs<Draft>(); $problems = $draft->problems(); } catch (ParseError $error) { $problems = ['Please fill in the form.']; } if (Core\Arr::count($problems) > 0) { // 422 means the server understood the request, but the data is not valid. Response::setStatus(422); Response::sendHtml(Pages::home($store->all(), $draft, $problems)); return; } $store->add($draft); // After a form is saved, the browser goes back to the home page. Response::redirect(Core\Router::url(App::home)); }
// Shows one note. #[Route(path: '/notes/{id}', method: Method::Get)] #[Access(allow: Audience::Public)] public static function show(uint $id): void { ?Note $note = App::store()->find($id); if ($note == null) { Response::setStatus(404); Response::sendHtml(Pages::notFound()); return; } Response::sendHtml(Pages::note($note)); }
// Returns every note as JSON. #[Route(path: '/api/notes', method: Method::Get)] #[Access(allow: Audience::Public)] public static function apiList(): void { Response::sendJson(App::store()->all()); }
// Returns one note as JSON. #[Route(path: '/api/notes/{id}', method: Method::Get)] #[Access(allow: Audience::Public)] public static function apiShow(uint $id): void { ?Note $note = App::store()->find($id); if ($note == null) { Response::setStatus(404); Response::sendJson({ error: 'There is no note with this number.' }); return; } Response::sendJson($note); }
// Saves a note from a JSON body such as `{"title": "Milk", "body": "Buy two"}`. #[Route(path: '/api/notes', method: Method::Post)] #[Access(allow: Audience::Public)] public static function apiAdd(): void { try { var $draft = Request::jsonAs<Draft>(); array<string> $problems = $draft->problems(); if (Core\Arr::count($problems) > 0) { Response::setStatus(422); Response::sendJson({ errors: $problems }); return; } // 201 means a new note was saved. Response::setStatus(201); Response::sendJson(App::store()->add($draft)); } catch (ParseError $error) { // A body that is not JSON, or that has a missing field, throws a `ParseError`. Response::setStatus(422); Response::sendJson({ errors: ['The body must be JSON with a title and a body.'] }); } }
// Opens the database `notes` from `nvs.toml` and creates the table when it is missing. private static function store(): Store { var $store = new Store(Db::connect('notes')); $store->setUp(); return $store; }}<?nvsnamespace Notes;
use Core\Http\Method;use Core\Str;use Core\Test;
// Tests that send requests to the app. `Test::request` runs the app without a server.// These requests do not save a note, so the file `notes.sqlite` stays the same.final class AppTest{ #[Test] public function theHomePageShowsTheForm(): void { var $response = Test::request(Method::Get, '/'); Test::assertEquals($response->status(), 200); Test::assertTrue(Str::contains($response->body(), "<form method=\"post\" action=\"/notes\">")); }
#[Test] public function aFormWithNoTitleShowsTheProblem(): void { array<string> $headers = ['content-type' => 'application/x-www-form-urlencoded']; var $response = Test::request(Method::Post, '/notes', { headers: $headers, body: 'title=&body=Buy+two' }); Test::assertEquals($response->status(), 422); Test::assertTrue(Str::contains($response->body(), 'Please enter a title.')); }
#[Test] public function theApiChecksTheJson(): void { array<string> $headers = ['content-type' => 'application/json']; var $response = Test::request(Method::Post, '/api/notes', { headers: $headers, body: "{\"title\": \"\", \"body\": \"\"}" }); Test::assertEquals($response->status(), 422); Test::assertSame($response->body(), "{\"errors\":[\"Please enter a title.\"]}"); }
#[Test] public function aMissingNoteIsNotFound(): void { Test::assertEquals(Test::request(Method::Get, '/api/notes/999999')->status(), 404); var $response = Test::request(Method::Get, '/no-such-page'); Test::assertEquals($response->status(), 404); Test::assertTrue(Str::contains($response->body(), 'There is no page at this address.')); }
#[Test] public function anErrorShowsTheFailurePage(): void { // This number is too large for the database, so `App::show` throws an error. var $response = Test::request(Method::Get, '/notes/18446744073709551615'); Test::assertEquals($response->status(), 500); Test::assertTrue(Str::contains($response->body(), 'Something went wrong')); }
#[Test] public function aWrongMethodIsNotAllowed(): void { // The path `/notes` has only a `POST` route. The `allow` header lists the methods it has. var $response = Test::request(Method::Delete, '/notes'); Test::assertEquals($response->status(), 405); Test::assertEquals($response->header('allow'), 'POST'); Test::assertTrue(Str::contains($response->body(), 'This address does not accept this kind of request.')); }
#[Test] public function aFormFromAnotherSiteIsRefused(): void { // The `origin` header shows that another website sent the form. array<string> $headers = [ 'content-type' => 'application/x-www-form-urlencoded', 'origin' => 'https://example.com', ]; var $response = Test::request(Method::Post, '/notes', { headers: $headers, body: 'title=Milk&body=Buy+two' }); Test::assertEquals($response->status(), 403); Test::assertTrue(Str::contains($response->body(), 'The form was not sent from this website')); }}<?nvsnamespace Notes;
use Core\Str;
// A note that a user sent and that is not saved yet.// The form and the JSON API both fill a `Draft`. Its text comes from the user, so it is `tainted`.#[Core\Json\Derive]final class Draft{ public tainted string $title; public tainted string $body;
public function constructor(tainted string $title, tainted string $body) { $this->title = $title; $this->body = $body; }
// Returns one message for each field that is not valid. An empty array means the draft is valid. public function problems(): array<string> { array<string> $problems = []; if (Str::trim($this->title) == '') { $problems[] = 'Please enter a title.'; } elseif (Str::length($this->title) > 100) { $problems[] = 'The title can have at most 100 characters.'; } if (Str::length($this->body) > 2000) { $problems[] = 'The note can have at most 2000 characters.'; } return $problems; }}<?nvsnamespace Notes;
use Core\Str;use Core\Test;
// Tests for the checks on a new note.final class DraftTest{ #[Test] public function aTitleAndATextAreValid(): void { Test::assertCount((new Draft('Milk', 'Buy two'))->problems(), 0); }
#[Test] public function aTitleWithOnlySpacesIsNotValid(): void { Test::assertEqualsDeep((new Draft(' ', 'Buy two'))->problems(), ['Please enter a title.']); }
#[Test] public function aLongTitleIsNotValid(): void { var $draft = new Draft(Str::repeat('a', 101), ''); Test::assertEqualsDeep($draft->problems(), ['The title can have at most 100 characters.']); }
#[Test] public function anEmptyTextIsValid(): void { Test::assertCount((new Draft('Milk', ''))->problems(), 0); }}<?nvsnamespace Notes;
use Core\Audience;use Core\Response;use Core\Router\Refusal;use Throwable;
// The gate of the app. `Core\Router::dispatch` calls it for every request.// It decides if a route method may run, and it shows the error pages.final class Gate implements Core\Router\Gate{ // Runs before each route method. The method runs only when this returns `true`. // Every route of this app is public, so this checks for `Audience::Public`. public function allows(Core\Router\Match $route): bool { return $route->accessAs<Audience>() == Audience::Public; }
// Shows a page when no route method can handle the request. // `dispatch` has already set the status code, such as 404 or 405. public function refused(Refusal $reason, ?Core\Router\Match $route): void { if ($reason == Refusal::NotFound) { Response::sendHtml(Pages::notFound()); return; } string $text = match ($reason) { Refusal::MethodNotAllowed => 'This address does not accept this kind of request.', Refusal::Csrf => 'The form was not sent from this website, so nothing was saved.', Refusal::BodyTooLarge => 'The note is too long.', default => 'This request is not allowed.', }; Response::sendHtml(Pages::problem('Not possible', $text)); }
// Shows a page when a route method throws an error, or when the app needs too much memory or time. // The status code is 500. public function failed(?Core\Router\Match $route, ?Throwable $error): void { Response::sendHtml(Pages::failed()); }}<?nvsnamespace Notes;
// One saved note: its number, its title and its text.// A user wrote the text, so it is `tainted`, also after it is saved.#[Core\Json\Derive]final class Note{ public uint $id; public tainted string $title; public tainted string $body;
public function constructor(uint $id, tainted string $title, tainted string $body) { $this->id = $id; $this->title = $title; $this->body = $body; }}<?nvsnamespace Notes;
use Core\Arr;use Core\Html\Markup;
// Builds the HTML pages. Each `{$name}` in an `html` literal is escaped, so a `<` in a note prints as `<`.final class Pages{ // The home page: a form for a new note, then every saved note. public static function home(array<Note> $notes, Draft $draft, array<string> $problems): Markup { tainted string $title = $draft->title; tainted string $body = $draft->body; var $form = html`<form method="post" action="/notes"><?= Pages::errorList($problems) ?><p><label>Title <input name="title" value="{$title}"></label></p><p><label>Note <textarea name="body">{$body}</textarea></label></p><p><button>Save</button></p></form>`; var $list = html``; foreach ($notes as Note $note) { // `Core\Router::url` builds the path of the route `App::show`, such as `/notes/3`. string $link = Core\Router::url(App::show, ['id' => $note->id]); tainted string $noteTitle = $note->title; $list = $list + html`<li><a href="{$link}">{$noteTitle}</a></li>`; } return Pages::layout('Notes', html`<h1>Notes</h1>{$form}<ul>{$list}</ul>`); }
// The page for one note. public static function note(Note $note): Markup { tainted string $title = $note->title; tainted string $body = $note->body; return Pages::layout($title, html`<h1>{$title}</h1><p>{$body}</p><p><a href="/">All notes</a></p>`); }
// The page for a path that has no route, or for a note that does not exist. public static function notFound(): Markup { return Pages::problem('Not found', 'There is no page at this address.'); }
// The page for an error in the app. public static function failed(): Markup { return Pages::problem('Something went wrong', 'Please try again later.'); }
// A page with a title, one sentence and a link to the home page. public static function problem(string $title, string $text): Markup { return Pages::layout($title, html`<h1>{$title}</h1><p>{$text}</p><p><a href="/">All notes</a></p>`); }
// Returns a list of the problems, or nothing when there are none. private static function errorList(array<string> $problems): Markup { if (Arr::count($problems) == 0) { return html``; } var $items = html``; foreach ($problems as string $problem) { $items = $items + html`<li>{$problem}</li>`; } return html`<ul class="errors">{$items}</ul>`; }
private static function layout(tainted string $title, Markup $content): Markup { return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{$title}</title></head><body>{$content}</body></html>`; }}<?nvsnamespace Notes;
use Core\Db\Connection;use Core\Db\Row;use Core\Str;
// Reads and saves notes in a database.final class Store{ private Connection $db;
public function constructor(Connection $db) { $this->db = $db; }
// Creates the table `notes` if it does not exist yet. public function setUp(): void { $this->db->execute('create table if not exists notes (id integer primary key, title text not null, body text not null)', []); }
// Returns every note. The newest note is first. public function all(): array<Note> { array<Note> $notes = []; var $rows = $this->db->query('select id, title, body from notes order by id desc', []); foreach ($rows as Row $row) { $notes[] = Store::toNote($row); } return $notes; }
// Returns the note with this number. If there is none, the result is `null`. public function find(uint $id): ?Note { var $rows = $this->db->query('select id, title, body from notes where id = ?', [$id]); foreach ($rows as Row $row) { return Store::toNote($row); } return null; }
// Saves a valid draft and returns the new note. // Each `?` is a placeholder. The database gets the text apart from the SQL, so the text cannot change the SQL. public function add(Draft $draft): Note { tainted string $title = Str::trim($draft->title); tainted string $body = $draft->body; var $write = $this->db->execute('insert into notes (title, body) values (?, ?)', [$title, $body]); return new Note($write->lastId() ?? 0, $title, $body); }
private static function toNote(Row $row): Note { return new Note($row->uint('id') ?? 0, $row->string('title') ?? '', $row->string('body') ?? ''); }}<?nvsnamespace Notes;
use Core\Db;use Core\Test;
// Tests for saving and reading notes. They use the database `scratch`, which is kept in memory.final class StoreTest{ #[Test] public function aSavedNoteCanBeFound(): void { var $store = StoreTest::emptyStore(); var $saved = $store->add(new Draft(' Milk ', 'Buy two')); // `add` removes the spaces around the title. Test::assertSame($saved->title as string, 'Milk'); Test::assertSame($store->find($saved->id)?->body as ?string, 'Buy two'); }
#[Test] public function theNewestNoteIsFirst(): void { var $store = StoreTest::emptyStore(); $store->add(new Draft('First', '')); $store->add(new Draft('Second', '')); var $notes = $store->all(); Test::assertCount($notes, 2); Test::assertSame($notes[0]->title as string, 'Second'); }
#[Test] public function aMissingNoteIsNull(): void { Test::assertNull(StoreTest::emptyStore()->find(42)); }
// Returns a store with no notes. All tests share the `scratch` database, so this deletes the notes of the last test. private static function emptyStore(): Store { var $db = Db::connect('scratch'); var $store = new Store($db); $store->setUp(); $db->execute('delete from notes', []); return $store; }}# Notes
A small web app written in Novis. It saves notes in SQLite, shows them as HTML pages and has a small JSON API.
Run these commands in this folder:
```shnvs serve public/index.nvs # open http://127.0.0.1:8142/nvs test . # runs the tests```
In a clone of the repository, `bun nv app notes` starts the app from any folder.
The page [Example apps: Notes](https://novis-lang.org/guides/example-apps/notes/) explains each file.Get it running
Section titled “Get it running”Install Novis first. Then download only the folder apps/notes of the Novis
repository. A sparse clone (a clone that checks out only the folders you name) does this:
git clone --depth 1 --filter=blob:none --sparse https://github.com/novis-lang/novis.gitcd novisgit sparse-checkout set apps/notescd apps/notesStart the server from the folder apps/notes:
nvs serve public/index.nvsOpen http://127.0.0.1:8142/ in your browser. The first request creates the file notes.sqlite in
the same folder. Your notes are kept there, so they are still there after a restart.
Run the tests
Section titled “Run the tests”nvs test .nvs test . reads every .nvs file in the folder as one program and runs each #[Test] method:
Notes\AppTest ✓ theHomePageShowsTheForm 12.4 ms ✓ aFormWithNoTitleShowsTheProblem 0.5 ms ✓ theApiChecksTheJson 0.2 ms ✓ aMissingNoteIsNotFound 0.4 ms ✓ anErrorShowsTheFailurePage 0.4 ms ✓ aWrongMethodIsNotAllowed 0.2 ms ✓ aFormFromAnotherSiteIsRefused 0.2 ms Notes\DraftTest ✓ aTitleAndATextAreValid 0.1 ms ✓ aTitleWithOnlySpacesIsNotValid 0.1 ms ✓ aLongTitleIsNotValid 0.1 ms ✓ anEmptyTextIsValid 0.0 ms Notes\StoreTest ✓ aSavedNoteCanBeFound 0.6 ms ✓ theNewestNoteIsFirst 0.3 ms ✓ aMissingNoteIsNull 0.2 ms
0 failed, 14 passed, 0 skipped, 0 flaky in 16 msWhat each file does
Section titled “What each file does”notes/ nvs.toml the configuration: the port, the two databases and the permission to open them public/ index.nvs the entry file: every request starts here src/ App.nvs the routes: one method for each kind of request AppTest.nvs sends requests to the app and checks the responses Draft.nvs a note from the form or the API, and the checks on it DraftTest.nvs tests the checks on a new note Gate.nvs decides which routes may run, and shows the error pages Note.nvs a saved note Pages.nvs the HTML pages Store.nvs reads and saves notes in the database StoreTest.nvs tests saving and reading notes[server] listen in nvs.toml sets the port of the server to 8142. The other example apps use
other ports, so you can run them at the same time.
nvs.toml names two SQLite databases. notes is the file notes.sqlite. scratch is kept in
memory, and only the tests use it. The section [capabilities.db] allows the app to open these two
databases. A database that is not in this list cannot be opened.
public/index.nvs has two lines. The autoload line reads each class Notes\... from the folder
src. Then it calls Core\Router::dispatch(new Notes\Gate()). dispatch finds the route that
matches the request and calls its method.
src/App.nvs has one method for each route. A #[Core\Route] attribute gives the path and the
HTTP method. A #[Core\Access] attribute says who may use the route. Every route of this app is
public.
src/Gate.nvs is the gate. dispatch calls it for every request, and it has three methods:
allowsruns before each route method. The route method runs only whenallowsreturnstrue.refusedshows a page when no route method can handle the request. Examples are a path with no route (404), a wrong HTTP method (405) and a form sent from another website (403).failedshows a page when a route method throws an error. The status is500.
dispatch sets the status code before it calls refused or failed, so the gate only shows the page.
src/Draft.nvs is a new note before it is saved. The form and the JSON API both create a Draft.
Its text came from the user, so it is tainted string. problems() returns one message for each
property that is not valid.
src/Store.nvs runs the SQL. Every value goes to the database as a ? placeholder. The text of a
note is never part of the SQL.
src/Pages.nvs builds each page with an html template. A value you put into it with {$name} is escaped.
A note with the title <b>Milk</b> shows those characters as text.
The routes
Section titled “The routes”| Method and path | What it does |
|---|---|
GET / |
Shows the form and every note, newest first. |
POST /notes |
Saves the note from the form, then goes back to /. If the form is not valid, it shows the form again with the status 422. |
GET /notes/{id} |
Shows one note. |
GET /api/notes |
Returns every note as JSON. |
GET /api/notes/{id} |
Returns one note as JSON, or the status 404. |
POST /api/notes |
Saves a note from a JSON body and returns it with the status 201. |
Try the API with curl while the server runs:
curl -H "content-type: application/json" -d '{"title": "Milk", "body": "Buy two"}' http://127.0.0.1:8142/api/notescurl http://127.0.0.1:8142/api/notesStart your own app from it
Section titled “Start your own app from it”- Copy the folder
apps/notesand give it the name of your app. - Choose a namespace for your app, for example
Shop. Changenamespace Notes;in each file undersrc/, and theautoloadline andNotes\Gateinpublic/index.nvs. - In
nvs.toml, rename the databasenotesand its file. Change the name in[capabilities.db]and in the call toCore\Db::connectinsrc/App.nvs. - Delete the classes you do not need, and their tests. Run
nvs test .after each change.
Notes has no login. Anybody who can open the page can write a note. Before you put an app like this on the internet, add a login and a CSRF token to each form. A CSRF token is a value that proves a form came from your own page.
- In
nvs.toml, setcsrf_keyunder[http]. The key is 32 random bytes, written in base64. - In the method that shows a form, call
Core\Csrf::token(). It returns the token, and the response sends the session cookie. - Put the token in a hidden field of the form:
<input type="hidden" name="_csrf" value="{$token}">
The server then checks the token of each Post request before your method runs. A request without
a valid token gets the status 403. The reference page of Core\Csrf::token
shows a whole form. Then read the security checklist.
Read more
Section titled “Read more”- Project layout explains the folders.
- Page through database rows shows more of
Core\Db. - Testing a page shows
Core\Test::request.
