HTTP Server

This commit is contained in:
Simon Cambier
2023-10-12 20:20:39 +02:00
parent e59f252cb4
commit 35d3eb04a9
4 changed files with 131 additions and 6 deletions

61
src/tools/api-server.ts Normal file
View File

@@ -0,0 +1,61 @@
import * as http from 'http'
import * as url from 'url'
import api from './api'
import { Notice } from 'obsidian'
export function getServer() {
const server = http.createServer(async function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader(
'Access-Control-Allow-Methods',
'GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE'
)
res.setHeader(
'Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin, Authorization,Accept,x-client-id, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, hypothesis-client-version'
)
res.setHeader('Access-Control-Allow-Credentials', 'true')
try {
if (req.url) {
// parse URL
const parsedUrl = url.parse(req.url, true)
console.log(parsedUrl)
if (parsedUrl.pathname === '/search') {
const q = parsedUrl.query.q as string
console.log(q)
const results = await api.search(q)
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(results))
}
else {
res.end()
}
}
} catch (e) {
res.statusCode = 500
res.end(e)
}
})
return {
listen(port: string) {
console.log(`Omnisearch - Starting HTTP server on port ${port}`)
server.listen({
port: parseInt(port),
host: 'localhost',
})
console.log(`Omnisearch - Started HTTP server on port ${port}`)
new Notice(`Omnisearch - Started HTTP server on port ${port}`)
},
close() {
server.close()
console.log(`Omnisearch - Terminated HTTP server`)
new Notice(`Omnisearch - Terminated HTTP server`)
},
}
}
export default getServer
export type StaticServer = ReturnType<typeof getServer>