Skip to content

Instantly share code, notes, and snippets.

@eyeccc
Last active September 18, 2018 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyeccc/e892fcf292b086b28d30977a4853b81a to your computer and use it in GitHub Desktop.
Save eyeccc/e892fcf292b086b28d30977a4853b81a to your computer and use it in GitHub Desktop.
type username = string;
type state = {userName: option(username)};
type action =
| SetUserName(option(username));
/* Webapi: https://github.com/reasonml-community/bs-webapi-incubator */
let redirectToLogin = () => {
let currentUrl = Webapi.Dom.location |> Webapi.Dom.Location.href |> Js.Global.encodeURIComponent;
let url = "https://myapi.net/login?redirect_url=" ++ currentUrl;
Webapi.Dom.location |. Webapi.Dom.Location.setHref(url)
};
let handleLoadUserName = (_payload, {ReasonReact.send}) =>
Js.Promise.(
Fetch.fetchWithInit(
"https://myapi.net/username",
Fetch.RequestInit.make(~credentials=Include, ())
)
|> then_(
(res) => {
let isOK = res |> Fetch.Response.ok;
if (isOK) {
res
|> Fetch.Response.json
|> Js.Promise.then_((r) => {Some(r |> NameJsonDecoder) |. SetUserName |> send; Js.Promise.resolve() } )
} else {
let status = res |> Fetch.Response.status;
let statusText = res |> Fetch.Response.statusText;
if (status == 401) {
redirectToLogin()
};
Js.Promise.resolve()
}
}
)
|> catch((err) => Js.log(err))
)
|> ignore;
let component = ReasonReact.reducerComponent("KeycloakAppV2");
let make = (_children) => {
...component,
initialState: () => {userName: None},
reducer: (action, state) =>
switch action {
| SetUserName(userName) => ReasonReact.Update({...state, userName})
},
didMount: ({handle}) => handle(handleLoadUserName, ()),
render: ({state}) =>
<div>
(
switch state.userName {
| Some(u) => <MaybeSomeSecuredComponents user=(u) />
| None => <div> ("You're not logged in" |> ReasonReact.str) </div>
}
)
</div>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment