create-acrylblends 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +10 -0
  2. package/dist/index.d.ts +15 -0
  3. package/dist/index.js +287 -14
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +6 -4
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/getting-started/aws-lambda.md +115 -0
  8. package/docs/framework/getting-started/bun.md +1 -3
  9. package/docs/framework/getting-started/cloudflare-pages.md +53 -0
  10. package/docs/framework/getting-started/cloudflare-workers.md +67 -0
  11. package/docs/framework/getting-started/deploy.md +5 -5
  12. package/docs/framework/getting-started/lambda-edge.md +41 -0
  13. package/docs/framework/getting-started/netlify.md +25 -0
  14. package/docs/framework/getting-started/other-runtimes.md +20 -9
  15. package/docs/framework/getting-started/service-worker.md +33 -0
  16. package/docs/framework/getting-started/vercel.md +28 -0
  17. package/docs/framework/guides/create-acrylblends.md +40 -2
  18. package/docs/framework/guides/data.md +202 -0
  19. package/docs/framework/guides/faq.md +2 -2
  20. package/docs/framework/guides/forms-and-sessions.md +34 -30
  21. package/docs/framework/helpers/conninfo.md +1 -1
  22. package/docs/framework/helpers/ssg.md +1 -1
  23. package/docs/framework/helpers/streaming.md +3 -2
  24. package/docs/framework/helpers/websocket.md +2 -2
  25. package/docs/framework/middleware/builtin/ip-restriction.md +1 -1
  26. package/docs/framework/upstream.json +3 -3
  27. package/package.json +3 -2
  28. package/templates/chat/gitignore +3 -2
  29. package/templates/chat/migrations/001-chat.sql +12 -0
  30. package/templates/chat/src/app.ts +4 -2
  31. package/templates/chat/src/chat-app.ts +22 -18
  32. package/templates/chat/src/db.ts +30 -36
  33. package/templates/chat/src/index.ts +9 -4
  34. package/templates/chat/test/chat.test.ts +21 -9
  35. package/templates/chat/test/server.test.ts +1 -1
  36. package/templates/notes/gitignore +3 -2
  37. package/templates/notes/migrations/001-notes.sql +18 -0
  38. package/templates/notes/src/app.ts +4 -3
  39. package/templates/notes/src/auth.ts +21 -19
  40. package/templates/notes/src/db.ts +40 -50
  41. package/templates/notes/src/index.ts +9 -4
  42. package/templates/notes/src/notes-app.ts +35 -29
  43. package/templates/notes/test/notes.test.ts +27 -20
  44. package/templates/notes/test/server.test.ts +1 -1
@@ -1,9 +1,9 @@
1
1
  import { __CLASS__ } from '__PACKAGE__'
2
+ import type { Db } from '__PACKAGE__/db'
2
3
  import { clientModules } from '__PACKAGE__/node-server'
3
4
  import { type StandardSchema, schemaValidator } from '__PACKAGE__/schema-validator'
4
5
  import { streamSSE } from '__PACKAGE__/streaming'
5
- import type { DatabaseSync } from 'node:sqlite'
6
- import { chatStore, openDb } from './db.ts'
6
+ import { chatStore } from './db.ts'
7
7
  import { type Llm, openAiCompatible } from './llm.ts'
8
8
  import { chatPage } from './page.tsx'
9
9
 
@@ -30,41 +30,45 @@ const ChatSchema: StandardSchema<ChatInput> = {
30
30
  },
31
31
  }
32
32
 
33
- export function createApp(db: DatabaseSync = openDb(), llm: Llm = openAiCompatible) {
33
+ export function createApp(db: Db, llm: Llm = openAiCompatible) {
34
34
  const store = chatStore(db)
35
35
  const app = new __CLASS__()
36
36
 
37
- app.get('/', (c) => {
37
+ app.get('/', async (c) => {
38
38
  const id = Number(c.req.query('c'))
39
- const current = Number.isInteger(id) ? store.conversation(id) : undefined
39
+ const current = Number.isInteger(id) ? await store.conversation(id) : undefined
40
40
  return c.html(
41
- chatPage(store.conversations(), current, current ? store.messages(current.id) : []),
41
+ chatPage(
42
+ await store.conversations(),
43
+ current,
44
+ current ? await store.messages(current.id) : [],
45
+ ),
42
46
  )
43
47
  })
44
48
 
45
- app.get('/api/conversations', (c) => c.json({ conversations: store.conversations() }))
46
- app.get('/api/conversations/:id', (c) => {
49
+ app.get('/api/conversations', async (c) => c.json({ conversations: await store.conversations() }))
50
+ app.get('/api/conversations/:id', async (c) => {
47
51
  const id = Number(c.req.param('id'))
48
- const conversation = store.conversation(id)
52
+ const conversation = await store.conversation(id)
49
53
  return conversation
50
- ? c.json({ conversation, messages: store.messages(id) })
54
+ ? c.json({ conversation, messages: await store.messages(id) })
51
55
  : c.json({ error: 'No such conversation.' }, 404)
52
56
  })
53
- app.delete('/api/conversations/:id', (c) =>
54
- store.remove(Number(c.req.param('id')))
57
+ app.delete('/api/conversations/:id', async (c) =>
58
+ (await store.remove(Number(c.req.param('id'))))
55
59
  ? c.json({ ok: true })
56
60
  : c.json({ error: 'No such conversation.' }, 404),
57
61
  )
58
62
 
59
63
  // The answer streams as Server-Sent Events: `meta` (the conversation id), then one `token` per piece, then `done`, or `error`.
60
64
  // The request's signal aborts when the client goes away (the Stop button, a closed tab); it is passed to the model call so the upstream request stops too.
61
- app.post('/api/chat', schemaValidator('json', ChatSchema), (c) => {
65
+ app.post('/api/chat', schemaValidator('json', ChatSchema), async (c) => {
62
66
  const { message, conversation } = c.req.valid('json')
63
- const known = conversation === undefined ? undefined : store.conversation(conversation)
67
+ const known = conversation === undefined ? undefined : await store.conversation(conversation)
64
68
  if (conversation !== undefined && !known) return c.json({ error: 'No such conversation.' }, 404)
65
- const id = known?.id ?? store.start(message)
66
- store.add(id, 'user', message)
67
- const history = store.messages(id).map(({ role, content }) => ({ role, content }))
69
+ const id = known?.id ?? (await store.start(message))
70
+ await store.add(id, 'user', message)
71
+ const history = (await store.messages(id)).map(({ role, content }) => ({ role, content }))
68
72
  const signal = c.req.raw.signal
69
73
  return streamSSE(c, async (stream) => {
70
74
  let answer = ''
@@ -86,7 +90,7 @@ export function createApp(db: DatabaseSync = openDb(), llm: Llm = openAiCompatib
86
90
  }
87
91
  } finally {
88
92
  // What arrived is kept, also when the reader pressed Stop.
89
- if (answer !== '') store.add(id, 'assistant', answer)
93
+ if (answer !== '') await store.add(id, 'assistant', answer)
90
94
  }
91
95
  })
92
96
  })
@@ -1,4 +1,6 @@
1
- import { DatabaseSync } from 'node:sqlite'
1
+ import type { Db } from '__PACKAGE__/db'
2
+ import { openDb } from '__PACKAGE__/db/sqlite'
3
+ import { fileURLToPath } from 'node:url'
2
4
 
3
5
  export interface Message {
4
6
  id: number
@@ -11,49 +13,41 @@ export interface Conversation {
11
13
  title: string
12
14
  }
13
15
 
14
- export function openDb(path = process.env.CHAT_DB ?? 'chat.db'): DatabaseSync {
15
- const db = new DatabaseSync(path)
16
- db.exec(`
17
- PRAGMA foreign_keys = ON;
18
- CREATE TABLE IF NOT EXISTS conversations (id INTEGER PRIMARY KEY, title TEXT NOT NULL, created_at TEXT NOT NULL);
19
- CREATE TABLE IF NOT EXISTS messages (
20
- id INTEGER PRIMARY KEY,
21
- conversation_id INTEGER NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
22
- role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
23
- content TEXT NOT NULL
24
- );
25
- `)
26
- return db
16
+ /** The folder of numbered SQL files (001-chat.sql, ...). Applied on start, each once, in one transaction. */
17
+ const MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))
18
+
19
+ /** Open the chat database and apply the migrations. Call `close` once, when the process stops. */
20
+ export function openChatDb(path = process.env.CHAT_DB ?? 'data/chat.sqlite') {
21
+ return openDb({ path, migrations: MIGRATIONS })
27
22
  }
28
23
 
29
- export function chatStore(db: DatabaseSync) {
24
+ export function chatStore(db: Db) {
30
25
  return {
31
- conversations: () =>
32
- db
33
- .prepare('SELECT id, title FROM conversations ORDER BY id DESC')
34
- .all() as unknown as Conversation[],
35
- conversation: (id: number) =>
36
- db.prepare('SELECT id, title FROM conversations WHERE id = ?').get(id) as unknown as
37
- | Conversation
38
- | undefined,
39
- messages: (id: number) =>
40
- db
41
- .prepare('SELECT * FROM messages WHERE conversation_id = ? ORDER BY id')
42
- .all(id) as unknown as Message[],
43
- start(title: string): number {
44
- const info = db
45
- .prepare('INSERT INTO conversations (title, created_at) VALUES (?, ?)')
46
- .run(title.slice(0, 60), new Date().toISOString())
47
- return Number(info.lastInsertRowid)
26
+ conversations: (): Promise<Conversation[]> =>
27
+ db.all<Conversation>('SELECT id, title FROM conversations ORDER BY id DESC'),
28
+ conversation: (id: number): Promise<Conversation | undefined> =>
29
+ db.get<Conversation>('SELECT id, title FROM conversations WHERE id = ?', id),
30
+ messages: (id: number): Promise<Message[]> =>
31
+ db.all<Message>('SELECT * FROM messages WHERE conversation_id = ? ORDER BY id', id),
32
+ async start(title: string): Promise<number> {
33
+ const row = await db.get<{ id: number }>(
34
+ 'INSERT INTO conversations (title, created_at) VALUES (?, ?) RETURNING id',
35
+ title.slice(0, 60),
36
+ new Date().toISOString(),
37
+ )
38
+ return row!.id
48
39
  },
49
- add(conversationId: number, role: Message['role'], content: string) {
50
- db.prepare('INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)').run(
40
+ async add(conversationId: number, role: Message['role'], content: string): Promise<void> {
41
+ await db.run(
42
+ 'INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)',
51
43
  conversationId,
52
44
  role,
53
45
  content,
54
46
  )
55
47
  },
56
- remove: (id: number) =>
57
- Number(db.prepare('DELETE FROM conversations WHERE id = ?').run(id).changes) > 0,
48
+ async remove(id: number): Promise<boolean> {
49
+ const { changes } = await db.run('DELETE FROM conversations WHERE id = ?', id)
50
+ return changes > 0
51
+ },
58
52
  }
59
53
  }
@@ -1,5 +1,5 @@
1
1
  import { serve } from '__PACKAGE__/node-server'
2
- import app, { db } from './app.ts'
2
+ import app, { close } from './app.ts'
3
3
 
4
4
  const port = Number(process.env.PORT || 3000)
5
5
  // Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
@@ -9,11 +9,16 @@ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
9
9
  console.log(`listening on http://${info.address}:${info.port}`)
10
10
  })
11
11
 
12
- // Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
12
+ // Stop taking requests, let the ones in flight finish, then close the database and exit. A connection that never ends cannot keep the process alive past 10 seconds.
13
13
  function shutdown(): void {
14
14
  server.close(() => {
15
- db.close()
16
- process.exit(0)
15
+ close().then(
16
+ () => process.exit(0),
17
+ (error) => {
18
+ console.error(error)
19
+ process.exit(1)
20
+ },
21
+ )
17
22
  })
18
23
  server.closeIdleConnections()
19
24
  setTimeout(() => process.exit(1), 10_000).unref()
@@ -1,9 +1,19 @@
1
+ import type { Db } from '__PACKAGE__/db'
1
2
  import assert from 'node:assert/strict'
2
- import { test } from 'node:test'
3
+ import { after, test } from 'node:test'
3
4
  import { createApp } from '../src/chat-app.ts'
4
- import { openDb } from '../src/db.ts'
5
+ import { openChatDb } from '../src/db.ts'
5
6
  import type { Llm } from '../src/llm.ts'
6
7
 
8
+ /** A fresh database in memory with the real migrations; every one is closed when the tests end. */
9
+ const closers: (() => Promise<void>)[] = []
10
+ after(() => Promise.all(closers.map((close) => close())))
11
+ async function memoryDb(): Promise<Db> {
12
+ const { db, close } = await openChatDb(':memory:')
13
+ closers.push(close)
14
+ return db
15
+ }
16
+
7
17
  /** A model that answers with fixed pieces and records what it was asked. */
8
18
  function mock(pieces: string[]) {
9
19
  const asked: { role: string; content: string }[][] = []
@@ -34,7 +44,7 @@ function events(text: string): [string, string][] {
34
44
 
35
45
  test('the answer streams as events: meta, one token per piece, done', async () => {
36
46
  const { llm } = mock(['Hel', 'lo ', 'there\nline'])
37
- const app = createApp(openDb(':memory:'), llm)
47
+ const app = createApp(await memoryDb(), llm)
38
48
  const res = await app.request('/api/chat', post({ message: 'hi' }))
39
49
  assert.equal(res.status, 200)
40
50
  assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/)
@@ -54,7 +64,7 @@ test('the answer streams as events: meta, one token per piece, done', async () =
54
64
 
55
65
  test('history is stored, sent back to the model, and listed', async () => {
56
66
  const { llm, asked } = mock(['ok'])
57
- const app = createApp(openDb(':memory:'), llm)
67
+ const app = createApp(await memoryDb(), llm)
58
68
  const first = events(
59
69
  await (await app.request('/api/chat', post({ message: 'first question' }))).text(),
60
70
  )
@@ -82,7 +92,7 @@ test('history is stored, sent back to the model, and listed', async () => {
82
92
 
83
93
  test('a bad message answers 400 with a message, an unknown conversation 404, and nothing reaches the model', async () => {
84
94
  const { llm, asked } = mock(['x'])
85
- const app = createApp(openDb(':memory:'), llm)
95
+ const app = createApp(await memoryDb(), llm)
86
96
  const empty = await app.request('/api/chat', post({ message: ' ' }))
87
97
  assert.equal(empty.status, 400)
88
98
  assert.match(JSON.stringify(await empty.json()), /Write a message/)
@@ -94,7 +104,7 @@ test('a bad message answers 400 with a message, an unknown conversation 404, and
94
104
  })
95
105
 
96
106
  test('a conversation can be deleted', async () => {
97
- const app = createApp(openDb(':memory:'), mock(['a']).llm)
107
+ const app = createApp(await memoryDb(), mock(['a']).llm)
98
108
  const first = events(await (await app.request('/api/chat', post({ message: 'hi' }))).text())
99
109
  const id = (JSON.parse(first[0]![1]) as { conversation: number }).conversation
100
110
  assert.equal((await app.request(`/api/conversations/${id}`, { method: 'DELETE' })).status, 200)
@@ -107,7 +117,7 @@ test('a failing model sends an error event with a plain message and no detail',
107
117
  yield 'partial '
108
118
  throw new Error('upstream secret detail')
109
119
  }
110
- const app = createApp(openDb(':memory:'), llm)
120
+ const app = createApp(await memoryDb(), llm)
111
121
  const text = await (await app.request('/api/chat', post({ message: 'hi' }))).text()
112
122
  assert.doesNotMatch(text, /secret detail/)
113
123
  const last = events(text).at(-1)
@@ -131,7 +141,7 @@ test('when the client goes away the model call is aborted and what arrived is ke
131
141
  if (signal.aborted) throw new DOMException('aborted', 'AbortError')
132
142
  yield 'never sent'
133
143
  }
134
- const db = openDb(':memory:')
144
+ const db = await memoryDb()
135
145
  const app = createApp(db, llm)
136
146
  const controller = new AbortController()
137
147
  const res = await app.request('/api/chat', {
@@ -145,7 +155,9 @@ test('when the client goes away the model call is aborted and what arrived is ke
145
155
  controller.abort()
146
156
  assert.equal(await aborted, true)
147
157
  await new Promise((resolve) => setTimeout(resolve, 50))
148
- const rows = db.prepare('SELECT role, content FROM messages ORDER BY id').all()
158
+ const rows = await db.all<{ role: string; content: string }>(
159
+ 'SELECT role, content FROM messages ORDER BY id',
160
+ )
149
161
  assert.deepEqual(
150
162
  rows.map((r) => `${r.role}:${r.content}`),
151
163
  ['user:hi', 'assistant:first '],
@@ -15,7 +15,7 @@ async function start(env: Record<string, string> = {}) {
15
15
  env: {
16
16
  ...process.env,
17
17
  PORT: '0',
18
- CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.db'),
18
+ CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.sqlite'),
19
19
  ...env,
20
20
  },
21
21
  stdio: ['ignore', 'pipe', 'inherit'],
@@ -1,5 +1,6 @@
1
1
  node_modules/
2
- *.db
3
- *.db-*
2
+ data/
3
+ *.sqlite
4
+ *.sqlite-*
4
5
  .acrylblends/
5
6
  dist/
@@ -0,0 +1,18 @@
1
+ CREATE TABLE users (
2
+ id INTEGER PRIMARY KEY,
3
+ email TEXT NOT NULL UNIQUE,
4
+ password_hash TEXT NOT NULL
5
+ );
6
+
7
+ CREATE TABLE sessions (
8
+ token TEXT PRIMARY KEY,
9
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
10
+ );
11
+
12
+ CREATE TABLE notes (
13
+ id INTEGER PRIMARY KEY,
14
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
15
+ title TEXT NOT NULL,
16
+ body TEXT NOT NULL,
17
+ updated_at TEXT NOT NULL
18
+ );
@@ -1,7 +1,8 @@
1
- import { openDb } from './db.ts'
1
+ import { openNotesDb } from './db.ts'
2
2
  import { createApp } from './notes-app.ts'
3
3
 
4
- /** The database is opened here, once, so the server can close it when it stops. */
5
- export const db = openDb()
4
+ /** The composition root: opens the database (once) and builds the app. `index.ts` serves it; the desktop shell does too, and calls `close` when it stops. */
5
+ const { db, close } = await openNotesDb()
6
6
 
7
+ export { close }
7
8
  export default createApp(db)
@@ -1,5 +1,5 @@
1
+ import type { Db } from '__PACKAGE__/db'
1
2
  import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
2
- import type { DatabaseSync } from 'node:sqlite'
3
3
  import { promisify } from 'node:util'
4
4
 
5
5
  const scryptAsync = promisify(scrypt) as (
@@ -22,34 +22,36 @@ export async function verifyPassword(password: string, stored: string): Promise<
22
22
  return timingSafeEqual(actual, expected)
23
23
  }
24
24
 
25
- export function authStore(db: DatabaseSync) {
25
+ export function authStore(db: Db) {
26
26
  return {
27
27
  findUser(email: string) {
28
- return db.prepare('SELECT id, email, password_hash FROM users WHERE email = ?').get(email) as
29
- | { id: number; email: string; password_hash: string }
30
- | undefined
28
+ return db.get<{ id: number; email: string; password_hash: string }>(
29
+ 'SELECT id, email, password_hash FROM users WHERE email = ?',
30
+ email,
31
+ )
31
32
  },
32
33
  async createUser(email: string, password: string): Promise<number> {
33
- const info = db
34
- .prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)')
35
- .run(email, await hashPassword(password))
36
- return Number(info.lastInsertRowid)
34
+ const user = await db.get<{ id: number }>(
35
+ 'INSERT INTO users (email, password_hash) VALUES (?, ?) RETURNING id',
36
+ email,
37
+ await hashPassword(password),
38
+ )
39
+ return user!.id
37
40
  },
38
- startSession(userId: number): string {
41
+ async startSession(userId: number): Promise<string> {
39
42
  const token = randomBytes(32).toString('hex')
40
- db.prepare('INSERT INTO sessions (token, user_id) VALUES (?, ?)').run(token, userId)
43
+ await db.run('INSERT INTO sessions (token, user_id) VALUES (?, ?)', token, userId)
41
44
  return token
42
45
  },
43
- userFor(token: string | undefined) {
46
+ async userFor(token: string | undefined) {
44
47
  if (!token) return undefined
45
- return db
46
- .prepare(
47
- 'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
48
- )
49
- .get(token) as { id: number; email: string } | undefined
48
+ return db.get<{ id: number; email: string }>(
49
+ 'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
50
+ token,
51
+ )
50
52
  },
51
- endSession(token: string) {
52
- db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
53
+ async endSession(token: string): Promise<void> {
54
+ await db.run('DELETE FROM sessions WHERE token = ?', token)
53
55
  },
54
56
  }
55
57
  }
@@ -1,4 +1,6 @@
1
- import { DatabaseSync } from 'node:sqlite'
1
+ import type { Db } from '__PACKAGE__/db'
2
+ import { openDb } from '__PACKAGE__/db/sqlite'
3
+ import { fileURLToPath } from 'node:url'
2
4
 
3
5
  export interface Note {
4
6
  id: number
@@ -8,63 +10,51 @@ export interface Note {
8
10
  updated_at: string
9
11
  }
10
12
 
11
- export function openDb(path = process.env.NOTES_DB ?? 'notes.db'): DatabaseSync {
12
- const db = new DatabaseSync(path)
13
- db.exec(`
14
- PRAGMA foreign_keys = ON;
15
- CREATE TABLE IF NOT EXISTS users (
16
- id INTEGER PRIMARY KEY,
17
- email TEXT NOT NULL UNIQUE,
18
- password_hash TEXT NOT NULL
19
- );
20
- CREATE TABLE IF NOT EXISTS sessions (
21
- token TEXT PRIMARY KEY,
22
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
23
- );
24
- CREATE TABLE IF NOT EXISTS notes (
25
- id INTEGER PRIMARY KEY,
26
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
27
- title TEXT NOT NULL,
28
- body TEXT NOT NULL,
29
- updated_at TEXT NOT NULL
30
- );
31
- `)
32
- return db
13
+ /** The folder of numbered SQL files (001-notes.sql, ...). Applied on start, each once, in one transaction. */
14
+ const MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))
15
+
16
+ /** Open the notes database and apply the migrations. Call `close` once, when the process stops. */
17
+ export function openNotesDb(path = process.env.NOTES_DB ?? 'data/notes.sqlite') {
18
+ return openDb({ path, migrations: MIGRATIONS })
33
19
  }
34
20
 
35
- export function notesStore(db: DatabaseSync) {
21
+ export function notesStore(db: Db) {
36
22
  return {
37
- list(userId: number, q = ''): Note[] {
23
+ list(userId: number, q = ''): Promise<Note[]> {
38
24
  const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`
39
- return db
40
- .prepare(
41
- `SELECT * FROM notes WHERE user_id = ? AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') ORDER BY updated_at DESC, id DESC`,
42
- )
43
- .all(userId, like, like) as unknown as Note[]
44
- },
45
- get(userId: number, id: number): Note | undefined {
46
- return db
47
- .prepare('SELECT * FROM notes WHERE id = ? AND user_id = ?')
48
- .get(id, userId) as unknown as Note | undefined
25
+ return db.all<Note>(
26
+ `SELECT * FROM notes WHERE user_id = ? AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') ORDER BY updated_at DESC, id DESC`,
27
+ userId,
28
+ like,
29
+ like,
30
+ )
49
31
  },
50
- create(userId: number, title: string, body: string): Note {
51
- const info = db
52
- .prepare('INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?)')
53
- .run(userId, title, body, new Date().toISOString())
54
- return this.get(userId, Number(info.lastInsertRowid))!
32
+ get(userId: number, id: number): Promise<Note | undefined> {
33
+ return db.get<Note>('SELECT * FROM notes WHERE id = ? AND user_id = ?', id, userId)
55
34
  },
56
- update(userId: number, id: number, title: string, body: string): Note | undefined {
57
- db.prepare(
58
- 'UPDATE notes SET title = ?, body = ?, updated_at = ? WHERE id = ? AND user_id = ?',
59
- ).run(title, body, new Date().toISOString(), id, userId)
60
- return this.get(userId, id)
35
+ async create(userId: number, title: string, body: string): Promise<Note> {
36
+ const note = await db.get<Note>(
37
+ 'INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?) RETURNING *',
38
+ userId,
39
+ title,
40
+ body,
41
+ new Date().toISOString(),
42
+ )
43
+ return note!
61
44
  },
62
- remove(userId: number, id: number): boolean {
63
- return (
64
- Number(
65
- db.prepare('DELETE FROM notes WHERE id = ? AND user_id = ?').run(id, userId).changes,
66
- ) > 0
45
+ update(userId: number, id: number, title: string, body: string): Promise<Note | undefined> {
46
+ return db.get<Note>(
47
+ 'UPDATE notes SET title = ?, body = ?, updated_at = ? WHERE id = ? AND user_id = ? RETURNING *',
48
+ title,
49
+ body,
50
+ new Date().toISOString(),
51
+ id,
52
+ userId,
67
53
  )
68
54
  },
55
+ async remove(userId: number, id: number): Promise<boolean> {
56
+ const { changes } = await db.run('DELETE FROM notes WHERE id = ? AND user_id = ?', id, userId)
57
+ return changes > 0
58
+ },
69
59
  }
70
60
  }
@@ -1,5 +1,5 @@
1
1
  import { serve } from '__PACKAGE__/node-server'
2
- import app, { db } from './app.ts'
2
+ import app, { close } from './app.ts'
3
3
 
4
4
  const port = Number(process.env.PORT || 3000)
5
5
  // Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
@@ -9,11 +9,16 @@ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
9
9
  console.log(`listening on http://${info.address}:${info.port}`)
10
10
  })
11
11
 
12
- // Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
12
+ // Stop taking requests, let the ones in flight finish, then close the database and exit. A connection that never ends cannot keep the process alive past 10 seconds.
13
13
  function shutdown(): void {
14
14
  server.close(() => {
15
- db.close()
16
- process.exit(0)
15
+ close().then(
16
+ () => process.exit(0),
17
+ (error) => {
18
+ console.error(error)
19
+ process.exit(1)
20
+ },
21
+ )
17
22
  })
18
23
  server.closeIdleConnections()
19
24
  setTimeout(() => process.exit(1), 10_000).unref()