-
Notifications
You must be signed in to change notification settings - Fork 0
/
nfts-server.js
executable file
·72 lines (58 loc) · 1.71 KB
/
nfts-server.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
#!/usr/bin/env node
import http from 'http'
import Database from 'better-sqlite3'
class Finder {
constructor(db) { this.db = db }
metatags(file, type) {
return this.db.prepare(`
SELECT name
FROM metatags
WHERE file = ? AND type = ?
`).all(file, type).map( v => v.name)
}
search(query) {
let fts; try {
fts = this.db.prepare(`
SELECT file,subject,date,snippet(fts,3,'<b>','</b>','...',64) AS snippet
FROM fts
WHERE body MATCH ?
ORDER BY rank LIMIT 50
`).all(query)
} catch (err) {
return err
}
return fts.map( v => {
v.tags = this.metatags(v.file, 'tag')
v.authors = this.metatags(v.file, 'author')
return v
})
}
}
let server = http.createServer(function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*')
if (req.method !== "GET") { return err(res, "not implemented") }
let url; try {
url = new URL(req.url, `http://${req.headers.host}`)
} catch {
return err(res, 'Usage: /?q=query')
}
let q = url.searchParams.get('q')
if (!q) return err(res, 'Usage: /?q=query')
let r = finder.search(q)
if (r instanceof Error) return err(res, r.message)
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(r))
})
if (process.argv.length < 3) {
console.error('Usage: PORT=1234 nfts-server db.sqlite3')
process.exit(1)
}
let finder = new Finder(new Database(process.argv[2]))
server.listen(process.env.PORT || 3000, function() {
console.error(`Listening: http://[${this.address().address}]:${this.address().port}`)
})
function err(res, msg, code = 400) {
res.statusCode = code
res.statusMessage = msg
res.end()
}