diff options
author | bptato <nincsnevem662@gmail.com> | 2023-07-01 23:31:39 +0200 |
---|---|---|
committer | bptato <nincsnevem662@gmail.com> | 2023-07-01 23:36:15 +0200 |
commit | 51da99365959f4fd35cef7b5f8f919386f2cf4ca (patch) | |
tree | 224426e877284c6199afa84291f07e530693f381 /src/io/headers.nim | |
parent | 2f74b628f3c91860860cc19fc07db5c304e8e6ed (diff) | |
download | chawan-51da99365959f4fd35cef7b5f8f919386f2cf4ca.tar.gz |
Factor out headers into separate module
Diffstat (limited to 'src/io/headers.nim')
-rw-r--r-- | src/io/headers.nim | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/src/io/headers.nim b/src/io/headers.nim new file mode 100644 index 00000000..3bc3659b --- /dev/null +++ b/src/io/headers.nim @@ -0,0 +1,64 @@ +import tables + +import js/javascript +import utils/twtstr + +type Headers* = ref object + table* {.jsget.}: Table[string, seq[string]] + +jsDestructor(Headers) + +proc fill*(headers: Headers, ctx: JSContext, val: JSValue) = + if isSequence(ctx, val): + let x = fromJS[seq[(string, string)]](ctx, val) + if x.isSome: + for (k, v) in x.get: + if k in headers.table: + headers.table[k].add(v) + else: + headers.table[k] = @[v] + else: + let x = fromJS[Table[string, string]](ctx, val) + if x.isSome: + for k, v in x.get: + if k in headers.table: + headers.table[k].add(v) + else: + headers.table[k] = @[v] + +func newHeaders*(): Headers = + new(result) + +func newHeaders*(ctx: JSContext, obj = none(JSValue)): Headers {.jsctor.} = + new(result) + if obj.isSome: + result.fill(ctx, obj.get) + +func newHeaders*(table: Table[string, string]): Headers = + new(result) + for k, v in table: + let k = k.toHeaderCase() + if k in result.table: + result.table[k].add(v) + else: + result.table[k] = @[v] + +proc add*(headers: var Headers, k, v: string) = + let k = k.toHeaderCase() + if k notin headers.table: + headers.table[k] = @[v] + else: + headers.table[k].add(v) + +proc `[]=`*(headers: var Headers, k, v: string) = + headers.table[k.toHeaderCase()] = @[v] + +func getOrDefault*(headers: Headers, k: string, default = ""): string = + let k = k.toHeaderCase() + if k in headers.table: + headers.table[k][0] + else: + default + +proc addHeadersModule*(ctx: JSContext) = + ctx.registerType(Headers) |