|
| 1 | +// TODO : use only one way to make http requests either Axios or Fetch |
| 2 | +module Create = { |
| 3 | + type t = { |
| 4 | + author: string, |
| 5 | + text: string, |
| 6 | + } |
| 7 | + |
| 8 | + let storeComment = async (comment: t) => { |
| 9 | + let _ = await Axios.post( |
| 10 | + "comments.json", |
| 11 | + { |
| 12 | + "author": comment.author, |
| 13 | + "text": comment.text, |
| 14 | + }, |
| 15 | + { |
| 16 | + "responseType": "json", |
| 17 | + "headers": { |
| 18 | + // see https://github.com/shakacode/react_on_rails/blob/249c69812474e0f532df432581bf5e618df0e1ec/node_package/src/Authenticity.ts#L13C1-L18C1 |
| 19 | + "X-CSRF-Token": ReactOnRails.authenticityToken(), |
| 20 | + "X-Requested-With": "XMLHttpRequest", |
| 21 | + }, |
| 22 | + }, |
| 23 | + ) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +module Fetch = { |
| 28 | + type t = { |
| 29 | + author: string, |
| 30 | + text: string, |
| 31 | + id: int, |
| 32 | + } |
| 33 | + |
| 34 | + type comments = array<t> |
| 35 | + |
| 36 | + type commentsRes = {comments: comments} |
| 37 | + |
| 38 | + let fetchComments = async (): result<comments, string> => { |
| 39 | + open Json.Decode |
| 40 | + |
| 41 | + let response = await Fetch.get("comments.json") |
| 42 | + let jsonRes = await response->Fetch.Response.json |
| 43 | + |
| 44 | + let jsonComment = Json.Decode.object(field => { |
| 45 | + author: field.required(. "author", string), |
| 46 | + text: field.required(. "text", string), |
| 47 | + id: field.required(. "id", int), |
| 48 | + }) |
| 49 | + |
| 50 | + let jsonComments = Json.Decode.object(field => { |
| 51 | + comments: field.required(. "comments", array(jsonComment)), |
| 52 | + }) |
| 53 | + |
| 54 | + switch jsonRes->Json.decode(jsonComments) { |
| 55 | + | Ok(decodedRes) => Ok(decodedRes.comments) |
| 56 | + | Error(e) => Error(e) |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments