about summary refs log tree commit diff stats
path: root/src/io/request.nim
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-04-30 18:59:19 +0200
committerbptato <nincsnevem662@gmail.com>2023-04-30 18:59:19 +0200
commit5db380ff789db24c6c48e2c513d9ca5ac7a606b3 (patch)
tree9296e1b88d48bf767df49cfbf08c43181da24b44 /src/io/request.nim
parentc235e638788b43ca752179341e429f4d7e090870 (diff)
parenta02c408f933aea6f405ed3c64ab151b01b33ae9e (diff)
downloadchawan-5db380ff789db24c6c48e2c513d9ca5ac7a606b3.tar.gz
Merge branch 'wip_fetch'
Diffstat (limited to 'src/io/request.nim')
-rw-r--r--src/io/request.nim27
1 files changed, 25 insertions, 2 deletions
diff --git a/src/io/request.nim b/src/io/request.nim
index 7c764449..6234ff1f 100644
--- a/src/io/request.nim
+++ b/src/io/request.nim
@@ -2,6 +2,7 @@ import options
 import streams
 import tables
 
+import bindings/quickjs
 import types/url
 import js/javascript
 import utils/twtstr
@@ -48,11 +49,14 @@ type
 
   Response* = ref object
     body*: Stream
+    bodyUsed* {.jsget.}: bool
     res* {.jsget.}: int
     contenttype* {.jsget.}: string
     status* {.jsget.}: int
     headers* {.jsget.}: HeaderList
     redirect*: Request
+    url*: URL #TODO should be urllist?
+    unregisterFun*: proc()
  
   ReadableStream* = ref object of Stream
     isource*: Stream
@@ -207,12 +211,31 @@ func getOrDefault*(headers: HeaderList, k: string, default = ""): string =
   else:
     default
 
-proc readAll*(response: Response): string {.jsfunc.} =
+proc text*(response: Response): string {.jsfunc.} =
+  #TODO: this looks pretty unsafe.
   result = response.body.readAll()
   response.body.close()
+  response.bodyUsed = true
+  response.unregisterFun()
+
+#TODO: get rid of this
+proc readAll*(response: Response): string {.jsfunc.} =
+  return response.text()
+
+proc Response_json*(ctx: JSContext, this: JSValue, argc: cint, argv: ptr JSValue): JSValue {.cdecl.} =
+  let op = getOpaque0(this)
+  if unlikely(not ctx.isInstanceOf(this, "Response") or op == nil):
+    return JS_ThrowTypeError(ctx, "Value is not an instance of %s", "Response")
+  let response = cast[Response](op)
+  var s = response.text()
+  return JS_ParseJSON(ctx, addr s[0], cast[csize_t](s.len), cstring"<input>")
 
+#TODO: this should be a property of body
 proc close*(response: Response) {.jsfunc.} =
+  #TODO: this looks pretty unsafe
   response.body.close()
+  response.bodyUsed = true
+  response.unregisterFun()
 
 func credentialsMode*(attribute: CORSAttribute): CredentialsMode =
   case attribute
@@ -223,5 +246,5 @@ func credentialsMode*(attribute: CORSAttribute): CredentialsMode =
 
 proc addRequestModule*(ctx: JSContext) =
   ctx.registerType(Request)
-  ctx.registerType(Response)
+  ctx.registerType(Response, extra_funcs = [TabFunc(name: "json", fun: Response_json)])
   ctx.registerType(HeaderList)