12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667letlog_src=Logs.Src.create"sihl.middleware.jsonparser"moduleLogs=(valLogs.src_loglog_src:Logs.LOG)letkey:Yojson.Safe.tOpium.Context.key=Opium.Context.Key.create("json",funjson->json|>Yojson.Safe.to_string|>Sexplib.Std.sexp_of_string);;exceptionJson_body_not_foundletfindreq=tryOpium.Context.find_exnkeyreq.Opium.Request.envwith|_->Logs.err(funm->m"No JSON body found");Logs.info(funm->m"Have you applied the JSON parser middleware for this route?");raiseJson_body_not_found;;letfind_optreq=trySome(findreq)with|_->None;;letsettokenreq=letenv=req.Opium.Request.envinletenv=Opium.Context.addkeytokenenvin{reqwithenv};;letmiddleware=letopenLwt.Syntaxinletfilterhandlerreq=matchreq.Opium.Request.methwith(* While GET requests can have bodies, they don't have any meaning and can
be ignored. Forms only support POST and GET as action methods. *)|`POST->letcontent_type=tryreq|>Opium.Request.header"Content-Type"|>Option.map(String.split_on_char';')|>Option.mapList.hdwith|_->Nonein(matchcontent_typewith|Some"application/json"->let*json_body=Opium.Request.to_jsonreqin(matchjson_bodywith|Somejson->letreq=setjsonreqinhandlerreq|None->letresponse_body=Format.sprintf{|"{"errors": ["Invalid JSON provided"]"}"|}inOpium.Response.of_plain_textresponse_body|>Opium.Response.set_status`Bad_request|>Lwt.return)|_->handlerreq)|_->handlerreqinRock.Middleware.create~name:"jsonparser"~filter;;