Select Git revision
-
Hugo Trentesaux authoredHugo Trentesaux authored
start.ts 2.54 KiB
import { TOPIC } from '../consts'
import { kubo } from '../kubo'
import { createServer } from 'http'
import type { IncomingMessage, ServerResponse } from 'http'
const port = process.env.SUBMIT_GATEWAY_LISTEN_PORT || 3000
const host = '127.0.0.1'
const postgatewayUrl = `http://${host}:${port}`
const GATEWAY_LANDING_PAGE = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Datapod Gateway</title>
</head>
<body>
<h1>Datapod Gateway</h1>
<p>Use POST requests to submit data programatically. Alternatively, you can submit data manually in the form below for testing purpose.</p>
<form method="post" action="${postgatewayUrl}" enctype='text/plain'>
Blocks as base64 json list:
<input type="text" name="blocks" size=100 placeholder="['index request cid', 'index request as base64', 'data as base 64', 'optional aditionnal data as base64'...]"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
`
// request handler
function handleRequest(request: IncomingMessage, response: ServerResponse<IncomingMessage>) {
// use post requests to submit data
if (request.method == 'POST') {
let body = ''
request.on('data', function (data) {
body += data
})
request.on('end', function () {
// hack to allow submitting data with form
if (body.startsWith('blocks=')) {
body = body.slice(7)
}
console.log('Body: ' + body)
try {
const blocks = JSON.parse(body)
let first = true
for (const b of blocks) {
// first item is the index request CID
if (first) {
kubo.pubsub.publish(TOPIC, new TextEncoder().encode(b + '\n'))
first = false
continue
}
// other items are blocks
const buffer = Buffer.from(b, 'base64')
const bytes = new Uint8Array(buffer)
kubo.block.put(bytes).then((cid) => {})
}
response.writeHead(200, { 'Content-Type': 'text/html' })
response.end('data received and forwarded<br/>' + JSON.stringify(blocks, null, 4))
} catch (e: any) {
response.writeHead(400, { 'Content-Type': 'text/html' })
response.end('invalid request\n' + e.toString())
}
})
} else {
var html = GATEWAY_LANDING_PAGE
response.writeHead(200, { 'Content-Type': 'text/html' })
response.end(html)
}
}
const server = createServer(handleRequest)
server.listen(port)
console.log(`Listening on ${postgatewayUrl}`)