about summary refs log tree commit diff stats
path: root/src/loader/response.nim
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-09-14 01:41:47 +0200
committerbptato <nincsnevem662@gmail.com>2023-09-14 02:01:21 +0200
commitc1b8338045716b25d664c0b8dd91eac0cb76480e (patch)
treea9c0a6763f180c2b6dd380aa880253ffc7685d85 /src/loader/response.nim
parentdb0798acccbedcef4b16737f6be0cf7388cc0528 (diff)
downloadchawan-c1b8338045716b25d664c0b8dd91eac0cb76480e.tar.gz
move around more modules
* ips -> io/
* loader related stuff -> loader/
* tempfile -> extern/
* buffer, forkserver -> server/
* lineedit, window -> display/
* cell -> types/
* opt -> types/
Diffstat (limited to 'src/loader/response.nim')
-rw-r--r--src/loader/response.nim74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/loader/response.nim b/src/loader/response.nim
new file mode 100644
index 00000000..5c95e3af
--- /dev/null
+++ b/src/loader/response.nim
@@ -0,0 +1,74 @@
+import streams
+
+import bindings/quickjs
+import io/promise
+import js/error
+import js/javascript
+import loader/headers
+import loader/request
+import types/url
+
+import chakasu/charset
+
+type
+  Response* = ref object
+    res*: int
+    fd*: int
+    body*: Stream
+    bodyUsed* {.jsget.}: bool
+    contenttype* {.jsget.}: string
+    status* {.jsget.}: uint16
+    headers* {.jsget.}: Headers
+    redirect*: Request
+    url*: URL #TODO should be urllist?
+    unregisterFun*: proc()
+    bodyRead*: Promise[string]
+    charset*: Charset
+
+jsDestructor(Response)
+
+proc newResponse*(res: int, request: Request, fd = -1, stream: Stream = nil):
+    Response =
+  return Response(
+    res: res,
+    url: request.url,
+    body: stream,
+    bodyRead: Promise[string](),
+    fd: fd
+  )
+
+func sok(response: Response): bool {.jsfget: "ok".} =
+  return response.status in 200u16 .. 299u16
+
+func surl(response: Response): string {.jsfget: "url".} =
+  return $response.url
+
+#TODO: this should be a property of body
+proc close*(response: Response) {.jsfunc.} =
+  response.bodyUsed = true
+  if response.unregisterFun != nil:
+    response.unregisterFun()
+  if response.body != nil:
+    response.body.close()
+
+proc text*(response: Response): Promise[JSResult[string]] {.jsfunc.} =
+  if response.bodyRead == nil:
+    let p = newPromise[JSResult[string]]()
+    let err = JSResult[string]
+      .err(newTypeError("Body has already been consumed"))
+    p.resolve(err)
+    return p
+  let bodyRead = response.bodyRead
+  response.bodyRead = nil
+  return bodyRead.then(proc(s: string): JSResult[string] =
+    ok(s))
+
+proc json(ctx: JSContext, this: Response): Promise[JSResult[JSValue]]
+    {.jsfunc.} =
+  return this.text().then(proc(s: JSResult[string]): JSResult[JSValue] =
+    let s = ?s
+    return ok(JS_ParseJSON(ctx, cstring(s), cast[csize_t](s.len),
+      cstring"<input>")))
+
+proc addResponseModule*(ctx: JSContext) =
+  ctx.registerType(Response)