Skip to content

Commit

Permalink
refactor: more readablity with lodash
Browse files Browse the repository at this point in the history
  • Loading branch information
rdubigny committed Oct 25, 2024
1 parent 2e830dc commit a69abf1
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 20 deletions.
33 changes: 13 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as client from "openid-client";
import session from "express-session";
import morgan from "morgan";
import bodyParser from "body-parser";
import { chain, isObject } from "lodash-es";

const port = parseInt(process.env.PORT, 10) || 3000;
const app = express();
Expand All @@ -18,18 +19,12 @@ app.use(
);
app.use(morgan("combined"));

const removeNullValues = (obj) =>
Object.entries(obj).reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {});

const objToUrlParams = (obj) =>
new URLSearchParams(
Object.fromEntries(
Object.entries(obj).map(([k, v]) => [
k,
// stringify objects
typeof v === "object" && v !== null ? JSON.stringify(v) : v,
]),
),
chain(obj)
.omitBy((v) => !v)
.mapValues((o) => (isObject(o) ? JSON.stringify(o) : o))
.value(),
);

const getCurrentUrl = (req) =>
Expand Down Expand Up @@ -90,14 +85,12 @@ const getAuthorizationControllerFactory = (extraParams) => {

const redirectUrl = client.buildAuthorizationUrl(
config,
objToUrlParams(
removeNullValues({
nonce,
state,
...AUTHORIZATION_DEFAULT_PARAMS,
...extraParams,
}),
),
objToUrlParams({
nonce,
state,
...AUTHORIZATION_DEFAULT_PARAMS,
...extraParams,
}),
);

res.redirect(redirectUrl);
Expand Down Expand Up @@ -193,10 +186,10 @@ app.post("/logout", async (req, res, next) => {
const config = await getProviderConfig();
const redirectUrl = client.buildEndSessionUrl(
config,
objToUrlParams(removeNullValues({
objToUrlParams({
post_logout_redirect_uri: `${process.env.HOST}/`,
id_token_hint,
})),
}),
);

res.redirect(redirectUrl);
Expand Down
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"ejs": "^3.1.10",
"express": "^4.21.1",
"express-session": "^1.18.1",
"lodash-es": "^4.17.21",
"morgan": "^1.10.0",
"openid-client": "^6.1.3"
},
Expand Down

0 comments on commit a69abf1

Please sign in to comment.