-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
72 lines (61 loc) · 1.92 KB
/
app.js
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
import { Application, Router, send } from "https://deno.land/x/oak/mod.ts";
import * as render from './render.js'
import { DB } from "https://deno.land/x/sqlite/mod.ts";
const db = new DB("blog.db");
db.query("CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, body TEXT)");
const router = new Router();
router.get('/', list)
.get('/post/new', add)
.get('/post/:id', show)
.post('/post', create)
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
app.use(async (ctx) => {
console.log('path=', ctx.request.url.pathname)
if (ctx.request.url.pathname.startsWith("/public/")) {
console.log('pass:', ctx.request.url.pathname)
await send(ctx, ctx.request.url.pathname, {
root: Deno.cwd(),
index: "index.html",
});
}
});
function query(sql) {
let list = []
for (const [id, title, body] of db.query(sql)) {
list.push({id, title, body})
}
return list
}
async function list(ctx) {
let posts = query("SELECT id, title, body FROM posts")
console.log('list:posts=', posts)
ctx.response.body = await render.list(posts);
}
async function add(ctx) {
ctx.response.body = await render.newPost();
}
async function show(ctx) {
const pid = ctx.params.id;
let posts = query(`SELECT id, title, body FROM posts WHERE id=${pid}`)
let post = posts[0]
console.log('show:post=', post)
if (!post) ctx.throw(404, 'invalid post id');
ctx.response.body = await render.show(post);
}
async function create(ctx) {
const body = ctx.request.body()
if (body.type === "form") {
const pairs = await body.value
const post = {}
for (const [key, value] of pairs) {
post[key] = value
}
console.log('create:post=', post)
db.query("INSERT INTO posts (title, body) VALUES (?, ?)", [post.title, post.body]);
ctx.response.redirect('/');
}
}
console.log('Server run at http://127.0.0.1:8000')
await app.listen({ port: 8000 });