Skip to content
This repository was archived by the owner on Jul 31, 2025. It is now read-only.

Commit 8a1fd9c

Browse files
author
v1rtl
committed
mongodb example
1 parent 808d303 commit 8a1fd9c

File tree

7 files changed

+111
-49
lines changed

7 files changed

+111
-49
lines changed

app.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// deno-lint-ignore-file
22
import { NextFunction, Router, Handler, Middleware, UseMethodParams } from 'https://esm.sh/@tinyhttp/router'
3+
export type { NextFunction, Router, Handler, Middleware, UseMethodParams }
34
import { onErrorHandler, ErrorHandler } from './onError.ts'
45
// import { setImmediate } from 'https://deno.land/std@0.88.0/node/timers.ts'
56
import rg from 'https://esm.sh/regexparam'

egg.json

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,9 @@
44
"entry": "./app.ts",
55
"description": "0-legacy, tiny & fast web framework as a replacement of Express",
66
"homepage": "https://github.com/talentlessguy/tinyhttp-deno",
7-
"version": "0.0.12",
8-
"ignore": [
9-
"./examples/**/*.ts"
10-
],
11-
"files": [
12-
"./**/*.ts",
13-
"README.md"
14-
],
7+
"version": "0.0.14",
8+
"ignore": ["./examples/**/*.ts"],
9+
"files": ["./**/*.ts", "README.md"],
1510
"checkFormat": false,
1611
"checkTests": false,
1712
"checkInstallation": false,

examples/basic/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Basic example
2+
3+
Basic tinyhttp example with simple routing and route pattern matching.
4+
5+
## Run
6+
7+
```sh
8+
deno run --allow-net server.ts
9+
```

examples/basic/server.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,23 @@ import { App } from '../../app.ts'
22

33
const app = new App()
44

5-
app.get('/', (req, res) => {
6-
res.send(`Hello on ${req.url} from Deno v${Deno.version.deno} and tinyhttp! 🦕`)
7-
})
5+
app
6+
.get('/', (req, res) => {
7+
const greeting = `Hello on ${req.url} from Deno v${Deno.version.deno} and tinyhttp! 🦕`
8+
res.format({
9+
html: () => `<h1>${greeting}</h1>`,
10+
text: () => greeting
11+
})
12+
})
13+
.get('/page/:page/', (req, res) => {
14+
res.status = 200
15+
res.send(`
16+
<h1>Some cool page</h1>
17+
<h2>URL</h2>
18+
${req.url}
19+
<h2>Params</h2>
20+
${JSON.stringify(req.params, null, 2)}
21+
`)
22+
})
823

9-
app.listen(3000, () => console.log(`Started on :3000`))
24+
app.listen(3000, () => console.log(`Listening on http://localhost:3000`))

examples/eta/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# EJS example
2+
3+
Basic example of using tinyhttp and [Eta](https://github.com/eta-dev/eta).
4+
5+
## Run
6+
7+
```sh
8+
deno run --allow-read --allow-net server.ts
9+
```

examples/mongodb/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# tinyhttp MongoDB example
2+
3+
A simple note app using [tinyhttp](https://github.com/talentlessguy/tinyhttp-deno) and [MongoDB](https://www.mongodb.com).
4+
5+
## Setup
6+
7+
1. Install MongoDB server.
8+
9+
## Run
10+
11+
```sh
12+
deno run --allow-env --allow-read --allow-net server.ts
13+
```
14+
15+
## Endpoints
16+
17+
- `GET /notes` - list notes with 2 properties which are title and desc.
18+
19+
- `POST /notes` - create a post using the data from `title` and `desc` query
20+
21+
- `DELETE /notes` - delete a note with specified ID
22+
23+
- `PUT /notes` - update a note by ID

examples/mongodb/server.ts

Lines changed: 47 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,77 @@
1-
import { App } from '../../app.ts'
2-
// import { MongoClient, Bson } from 'https://deno.land/x/mongo@v0.21.0/mod.ts'
3-
// import * as dotenv from 'https://deno.land/x/dotenv/mod.ts'
1+
import { App, Handler } from '../../app.ts'
2+
import { Request } from '../../request.ts'
3+
import { MongoClient, Bson } from 'https://deno.land/x/mongo@v0.21.2/mod.ts'
4+
import * as dotenv from 'https://deno.land/x/tiny_env@1.0.0/mod.ts'
45

5-
// dotenv.config()
6+
dotenv.load()
67

7-
const app = new App()
8+
type Req = Request & {
9+
bodyResult: any
10+
}
11+
12+
const app = new App<any, Req>({
13+
onError: (err, req) => {
14+
console.log(err)
15+
req.respond({ body: 'Error' })
16+
}
17+
})
818
const port = parseInt(Deno.env.get('PORT') || '') || 3000
919

1020
// connect to mongodb
11-
/* const client = new MongoClient()
21+
const client = new MongoClient()
1222

1323
await client.connect(Deno.env.get('DB_URI') || '')
1424

1525
const db = client.database('notes')
16-
const coll = db.collection('notes') */
17-
18-
app.get(async (req, res) => {
19-
const buf: Uint8Array = await Deno.readAll(req.body)
20-
21-
console.log(buf.toString())
26+
const coll = db.collection('notes')
2227

23-
res.send('bruh')
24-
})
25-
26-
/* // get all notes
28+
// get all notes
2729
app.get('/notes', async (_, res, next) => {
2830
try {
2931
const r = await coll.find({}).toArray()
32+
3033
res.send(r)
3134
next()
3235
} catch (err) {
3336
next(err)
3437
}
3538
})
3639

40+
const bodyParser: Handler<Req> = async (req, res, next) => {
41+
const buf = await Deno.readAll(req.body)
42+
43+
const dec = new TextDecoder()
44+
45+
const body = dec.decode(buf)
46+
47+
try {
48+
const result = JSON.parse(body)
49+
req.bodyResult = result
50+
} catch (e) {
51+
next(e)
52+
}
53+
next()
54+
}
55+
app.use(bodyParser)
56+
3757
// add new note
3858
app.post('/notes', async (req, res, next) => {
3959
try {
60+
const { title, desc } = req.bodyResult
61+
const r = await coll.insertOne({ title, desc })
4062

41-
42-
if (result?.value) {
43-
const { title, desc } = result.value
44-
const r = await coll.insertOne({ title, desc })
45-
assertStrictEquals(1, r.insertedCount)
46-
res.send(`Note with title of "${title}" has been added`)
47-
} else {
48-
next('No body provided')
49-
}
63+
res.send(`Note with title of "${title}" has been added`)
5064
} catch (err) {
5165
next(err)
5266
}
5367
})
54-
*/
55-
/* // delete note
68+
69+
// delete note
5670
app.delete('/notes', async (req, res, next) => {
5771
try {
58-
const { id } = req.body
59-
const r = await coll.deleteOne({ _id: new Bson.ObjectId(id) })
60-
assertStrictEquals(1, r)
72+
const { id } = req.bodyResult
73+
await coll.deleteOne({ _id: new Bson.ObjectId(id) })
74+
6175
res.send(`Note with id of ${id} has been deleted`)
6276
} catch (err) {
6377
next(err)
@@ -67,16 +81,12 @@ app.delete('/notes', async (req, res, next) => {
6781
// update existing note
6882
app.put('/notes', async (req, res, next) => {
6983
try {
70-
const { title, desc, id } = req.body
71-
await coll.findOneAndUpdate(
72-
{ _id: new mongodb.ObjectId(id) },
73-
{ $set: { title, desc } },
74-
{ returnOriginal: false, upsert: true }
75-
)
84+
const { title, desc, id } = req.bodyResult
85+
await coll.updateOne({ _id: new Bson.ObjectId(id) }, { $set: { title, desc } })
7686
res.send(`Note with title of ${title} has been updated`)
7787
} catch (err) {
7888
next(err)
7989
}
8090
})
81-
*/
91+
8292
app.listen(port, () => console.log(`Started on http://localhost:${port}`))

0 commit comments

Comments
 (0)