diff options
Diffstat (limited to 'src/io')
-rw-r--r-- | src/io/loader.nim | 6 | ||||
-rw-r--r-- | src/io/response.nim | 25 |
2 files changed, 24 insertions, 7 deletions
diff --git a/src/io/loader.nim b/src/io/loader.nim index acc432ec..0ce19c38 100644 --- a/src/io/loader.nim +++ b/src/io/loader.nim @@ -60,6 +60,7 @@ type buf: string readbufsize: int response: Response + bodyRead: Promise[string] ConnectErrorCode* = enum ERROR_SOURCE_NOT_FOUND = (-4, "clone source could not be found"), @@ -295,6 +296,7 @@ proc onConnected*(loader: FileLoader, fd: int) = loader.ongoing[fd] = OngoingData( response: response, readbufsize: BufferSize, + bodyRead: response.bodyRead ) SocketStream(stream).source.getFd().setBlocking(false) promise.resolve(Result[Response, JSError].ok(response)) @@ -319,7 +321,9 @@ proc onRead*(loader: FileLoader, fd: int) = buffer[].readbufsize = min(BufferSize, buffer[].readbufsize * 2) buffer[].buf.setLen(olen + n) if response.body.atEnd(): - response.bodyRead.resolve(buffer[].buf) + buffer[].bodyRead.resolve(buffer[].buf) + buffer[].bodyRead = nil + buffer[].buf = "" response.unregisterFun() break except ErrorAgain, ErrorWouldBlock: diff --git a/src/io/response.nim b/src/io/response.nim index 2c336a8c..fbe5339e 100644 --- a/src/io/response.nim +++ b/src/io/response.nim @@ -3,6 +3,7 @@ import streams import bindings/quickjs import io/promise import io/request +import js/exception import js/javascript import types/url @@ -44,13 +45,25 @@ proc close*(response: Response) {.jsfunc.} = if response.body != nil: response.body.close() -proc text*(response: Response): Promise[string] {.jsfunc.} = - return response.bodyRead +proc text*(response: Response): Promise[Result[string, JSError]] {.jsfunc.} = + if response.bodyRead == nil: + let p = Promise[Result[string, JSError]]() + let err = Result[string, JSError] + .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): Result[string, JSError] = + ok(s)) -proc json(ctx: JSContext, this: Response): Promise[JSValue] {.jsfunc.} = - return this.text().then(proc(s: string): JSValue = - return JS_ParseJSON(ctx, cstring(s), cast[csize_t](s.len), - cstring"<input>")) +proc json(ctx: JSContext, this: Response): Promise[Result[JSValue, JSError]] + {.jsfunc.} = + return this.text().then(proc(s: Result[string, JSError]): + Result[JSValue, JSError] = + let s = ?s + return ok(JS_ParseJSON(ctx, cstring(s), cast[csize_t](s.len), + cstring"<input>"))) proc addResponseModule*(ctx: JSContext) = ctx.registerType(Response) |