Skip to content

Instantly share code, notes, and snippets.

@twilson63
Last active Jun 24, 2021
Embed
What would you like to do?
p2p Database workshop initial server code
const { Client } = require('hyperspace')
const Hyperbee = require('hyperbee')
const client = new Client()
const store = client.corestore()
const core = store.get('ee26ef1982c9f3bb3ce49adc46cbc55467ecb88779a629234af702da9965758e')
const db = new Hyperbee(core, {
keyEncoding: 'utf-8',
valueEncoding: 'json'
})
// list movies
exports.list = async function () {
var movies = []
await new Promise(r => {
db.createReadStream()
.on('data', entry => movies.push(entry.value))
.on('end', r)
})
return movies
}
const express = require('express')
const index = `<!doctype html>
<html>
<head>
<title>p2p Db Demo</title>
<script src="https://unpkg.com/htmx.org@1.4.1"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script>
<script src="https://unpkg.com/hyperscript.org@0.8.1"></script>
</head>
<body>
<h1>p2p Db Demo</h1>
<h2>Movies</h2>
<form hx-post="/" hx-ext="json-enc" hx-target="#movies" _="on htmx:afterRequest reset() me">
<legend>Add movie</legend>
<label for="title">Title</label>
<input type="text" name="title" id="title" />
<button type="submit">Add</button>
<button type="reset">Reset</button>
</form>
<div>
<h3>Current Movie List</h3>
<div id="movies" hx-get="/movies" hx-trigger="load">
</div>
</div>
</body>
</html>
`
const app = express()
app.get('/movies', (req, res) => {
res.setHeader('content-type', 'text/html')
res.send('<li>Movie</li>')
})
app.post('/', express.json(), (req, res) => {
res.setHeader('content-type', 'text/html')
res.send(`<li>${req.body.title}</li>`)
})
app.get('/', (req, res) => {
res.setHeader('content-type', 'text/html')
res.send(index)
})
app.listen(3000)
const express = require('express')
const { add, list } = require('./db')
const index = `<!doctype html>
<html>
<head>
<title>p2p Db Demo</title>
<script src="https://unpkg.com/htmx.org@1.4.1"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script>
<script src="https://unpkg.com/hyperscript.org@0.8.1"></script>
</head>
<body>
<h1>p2p Db Demo</h1>
<h2>Movies</h2>
<div>
<h3>Current Movie List</h3>
<div id="movies" hx-get="/movies" hx-trigger="load">
</div>
</div>
</body>
</html>
`
const app = express()
app.get('/movies', async (req, res) => {
const s = await list()
res.setHeader('content-type', 'text/html')
res.send(s.map(m => `<li>${m.title}</li>`).join(''))
})
app.post('/', express.json(), async (req, res) => {
await add(req.body)
const s = await list()
res.setHeader('content-type', 'text/html')
res.send(s.map(m => `<li>${m.title}</li>`).join(''))
})
app.get('/', async (req, res) => {
res.setHeader('content-type', 'text/html')
res.send(index)
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment