1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { sqlite } from "https://esm.town/v/std/sqlite";
import { asc, desc, eq, sql, or, like } from "npm:drizzle-orm";
import { drizzle } from "npm:drizzle-orm/libsql";
import { integer, sqliteTable, text } from "npm:drizzle-orm/sqlite-core";
export type BedtimeStory = {
color: string;
animal: string;
adjective: string;
activity: string;
title: string;
story: string;
summary: string;
pictureUrl: string;
};
const bedtimeStories = sqliteTable("bedtime_stories", {
id: integer('id').primaryKey(),
color: text("color").notNull(),
animal: text("animal").notNull(),
adjective: text("adjective").notNull(),
activity: text("activity").notNull(),
title: text("title").notNull(),
story: text("story").notNull(),
summary: text("summary"),
pictureUrl: text("picture_url"),
});
const schema = { bedtimeStories };
const db = drizzle(sqlite as any, { schema });
export const setupDB = async (reset = false) => {
if (reset) {
await sqlite.execute(`DROP TABLE bedtime_stories`);
}
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS bedtime_stories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
color TEXT NOT NULL,
animal TEXT NOT NULL,
adjective TEXT NOT NULL,
activity TEXT NOT NULL,
title TEXT NOT NULL,
story TEXT NOT NULL,
summary TEXT,
picture_url TEXT
);`);
return;
};
// query all bedtime stories
export const getAllBedtimeStories = async () => {
await setupDB();
// sort by title
return db.query.bedtimeStories.findMany({
orderBy: [asc(bedtimeStories.title)],
});
};
export const getBedtimeStoryById = async ( id: BedtimeStory['id']) : BedtimeStory => {
await setupDB();
return db.query.bedtimeStories.findFirst({
where: eq(bedtimeStories.id, id),
});
};
export const createBedtimeStory = async (
story: BedtimeStory
) => {
await setupDB();
// return db.insert(bedtimeStories).values(story);
console.log('>>> createBedtimeStory', story);
const result = await db.insert(bedtimeStories).values(story);
console.log('>>> createBedtimeStory', result, result.lastInsertRowid);
const createdStory = await getBedtimeStoryById(result.lastInsertRowid);
return createdStory;
};
// update bedtime story with summary and pictureUrl
export const updateBedtimeStoryWithSummaryAndPictureUrl = async (
id: number,
summary: string,
pictureUrl: string
) => {
await setupDB();
return db
.update(bedtimeStories)
.set({ summary: summary, pictureUrl: pictureUrl })
.where(eq(bedtimeStories.id, id));
};
// get recent bedtime stories limited by default
export const getRecentBedtimeStories = async (
limit: number
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 4, 2024