json-rpc.k 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. \d json
  2. \l json.k
  3. \d .
  4. ec:!/+((`ParseError ;-32700)
  5. (`InvalidRequest ;-32600)
  6. (`MethodNotFound ;-32601)
  7. (`InvalidParams ;-32602)
  8. (`InternalError ;-32603)
  9. (`ServerNotInitialized;-32002)
  10. (`UnknownErrorCode ;-32001))
  11. J:("jsonrpc";"2.0")
  12. not:{(J;("method";x)),$[#y;,("params";y);()]}
  13. req:{not[x;z],,("id";_y)}
  14. rpl:{(J;("id";_x);("result";y))}
  15. err:{(J;("id";_x);("error";!/+(,("code";y)),z))}
  16. pe:{err[`null;ec`ParseError;,("message";"json parse error")]}
  17. msg:{x}
  18. ie:{err[(x["id"];`null)[y];ec`InvalidRequest;,("message";"invalid request")]}
  19. / accomodate for parser by forcing symbols and flooring ints
  20. vld:{$[~*c:~^(!x)?("jsonrpc";"id";"method");0
  21. (~c[2])|~`C~@x"jsonrpc";0
  22. c[1]&^`i`C`s?t:@x"id";0
  23. c[1]&(`s~t)&~`null~x"id";0;1]}
  24. err0:{`err@"WHOOPS",`k@x}
  25. LKUP:(,"dummy")!{}
  26. nme:{z;err[(x"id";`null)@*^(!x)?,"id";ec`MethodNotFound;,("message";"method \"",(x"method"),"\" not found")]}
  27. lkup:{$[mth:.[.:;`$x"method";{::}];mth;~^(!LKUP)?x"method";LKUP@x"method";nme[x]]}
  28. hdl:{$[~vld[x];:ie[x;*^(!x)?,"id"];];res:(lkup[x])[x"params"];$[^*(!x)?,"id";res;rpl[x"id";res]]}
  29. / Maybe wrap in try and return `InternalError on errors that bubble up?
  30. recv:{$[(::)~r:.[json.prs;,x;{::}];pe[x];~/1_:\@r;msg@,hdl@r;msg@hdl'r]}