Skip to content

Instantly share code, notes, and snippets.

@terurou
Created April 26, 2022 08:29
Show Gist options
  • Save terurou/c5bf7b8429e22da4d75139142b7317eb to your computer and use it in GitHub Desktop.
Save terurou/c5bf7b8429e22da4d75139142b7317eb to your computer and use it in GitHub Desktop.
urql with Firebase Authentidation on Haxe/JS.
final client = UrqlReact.createClient({
url: "http://localhost:8080/",
requestPolicy: CacheAndNetwork,
exchanges: [
Urql.dedupExchange,
Urql.cacheExchange,
(input:ExchangeInput) -> {
(ops:Source<Operation>) -> {
final auth = Authenticaton.getAuth(); //firebase authentication
pipe(
ops,
mergeMap((operation:Operation) -> {
final currentUser = auth.currentUser;
if (currentUser != null) {
fromPromise(currentUser.getIdToken(true).then(token -> {
final fetchOptions = if (operation.context.fetchOptions == null) {
({} : RequestInit);
} else if (Syntax.typeof(operation.context.fetchOptions) == "function") {
(operation.context.fetchOptions : ()->RequestInit)();
} else {
(operation.context.fetchOptions : RequestInit);
}
final headers = new Headers(fetchOptions.headers);
headers.set("Authorization", 'Bearer ${token}');
Urql.makeOperation(operation.kind, operation, {
additionalTypenames: operation.context.additionalTypenames,
preferGetMethod: operation.context.preferGetMethod,
suspense: operation.context.suspense,
meta: operation.context.meta,
url: operation.context.url,
requestPolicy: operation.context.requestPolicy,
fetchOptions: {
// headers: headers, <- not work
headers: {
"Authorization": 'Bearer ${token}'
},
body: fetchOptions.body,
cache: fetchOptions.cache,
credentials: fetchOptions.credentials,
integrity: fetchOptions.integrity,
method: fetchOptions.method,
mode: fetchOptions.mode,
observe: fetchOptions.observe,
redirect: fetchOptions.redirect,
referrer: fetchOptions.referrer,
referrerPolicy: fetchOptions.referrerPolicy,
signal: fetchOptions.signal
},
fetch: operation.context.fetch
});
}));
} else {
ops;
}
}),
input.forward
);
}
},
Urql.fetchExchange
]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment