refactor: use Options instead of Errors

This commit is contained in:
rusconn
2023-06-01 13:40:06 +09:00
parent 2b6d346b74
commit d935d0579f
8 changed files with 51 additions and 55 deletions

3
lib/json.ts Normal file
View File

@@ -0,0 +1,3 @@
import { tryCatchK } from "fp-ts/lib/Option";
export const safeJsonParse = tryCatchK(JSON.parse);

View File

@@ -1,22 +1,16 @@
import * as O from "fp-ts/lib/Option";
import jwt_decode from "jwt-decode";
const safeJwtDecode = O.tryCatchK(jwt_decode);
export const decode = (token: string) => {
let headerObj;
let payloadObj;
let header: O.Option<Record<string, unknown>> = O.none;
let payload: O.Option<unknown> = O.none;
if (token.split(".").length === 3) {
/* eslint-disable no-empty */
try {
headerObj = jwt_decode(token, { header: true });
} catch {}
try {
payloadObj = jwt_decode(token, { header: false });
} catch {}
/* eslint-enable no-empty */
header = safeJwtDecode(token, { header: true });
payload = safeJwtDecode(token, { header: false });
}
return { headerObj, payloadObj };
return { header, payload };
};

4
lib/uri.ts Normal file
View File

@@ -0,0 +1,4 @@
import { tryCatchK } from "fp-ts/lib/Option";
export const safeEncodeURIComponent = tryCatchK(encodeURIComponent);
export const safeDecodeURIComponent = tryCatchK(decodeURIComponent);

4
lib/yaml.ts Normal file
View File

@@ -0,0 +1,4 @@
import { tryCatchK } from "fp-ts/lib/Option";
import YAML from "yaml";
export const safeYamlParse = tryCatchK(YAML.parse);