Skip to content

Commit

Permalink
Enable goConfig to infer its return type
Browse files Browse the repository at this point in the history
By adding some extra typescript magic
  • Loading branch information
spaceo committed Nov 21, 2024
1 parent f8e5591 commit 2f75108
Show file tree
Hide file tree
Showing 11 changed files with 30 additions and 27 deletions.
2 changes: 1 addition & 1 deletion app/auth/token/refresh/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const sessionTokenSchema = z.object({
})

export async function GET(request: NextRequest, response: NextResponse) {
const appUrl = goConfig<string>("app.url")
const appUrl = goConfig("app.url")
const session = await getSession()
const frontpage = `${appUrl}/`

Expand Down
2 changes: 1 addition & 1 deletion app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Image from "next/image"

import goConfig from "@/lib/config/config"

const wellknownUrl = goConfig<Promise<string | undefined>>("service.unilogin.wellknown.url")
const wellknownUrl = goConfig("service.unilogin.wellknown.url")
export default async function Home() {
return (
<div
Expand Down
2 changes: 1 addition & 1 deletion codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const config: CodegenConfig = {
documents: "**/*.fbi.graphql",
schema: [
{
[goConfig<string>("service.fbi.graphql.endpoint")]: {
[String(goConfig("service.fbi.graphql.endpoint"))]: {
headers: {
Authorization: `Bearer ${goConfig("token.adgangsplatformen.library")}`,
},
Expand Down
13 changes: 6 additions & 7 deletions components/pages/searchPageLayout/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ReadonlyURLSearchParams } from "next/navigation"

import { getFacetMachineNames } from "@/components/shared/searchFilters/helper"
import goConfig from "@/lib/config/config"
import { TConfigSearchFacets } from "@/lib/config/resolvers/search"
import { SearchFiltersInput, SearchWithPaginationQuery } from "@/lib/graphql/generated/fbi/graphql"
import { TFilters } from "@/lib/machines/search/types"
import useSearchMachineActor from "@/lib/machines/search/useSearchMachineActor"
Expand All @@ -18,29 +17,29 @@ export const getSearchQueryArguments = ({
currentPage: number
facetFilters: SearchFiltersInput
}) => {
const limit = goConfig<number>("search.item.limit")
const limit = goConfig("search.item.limit")
return {
q: { all: q },
offset: currentPage * limit,
limit: limit,
filters: {
branchId: goConfig<`${number}`[]>("search.branch.ids"),
branchId: goConfig("search.branch.ids"),
...facetFilters,
},
}
}

export const getFacetsForSearchRequest = (searchParams: ReadonlyURLSearchParams) => {
const facets = goConfig<TConfigSearchFacets>("search.facets")
const facets = goConfig("search.facets")
const facetsMachineNames = getFacetMachineNames()

return facetsMachineNames.reduce(
(acc: TFilters, machineName) => {
const values = searchParams.getAll(facets[machineName].filter)
const values = searchParams.getAll(facets[machineName as keyof typeof facets].filter)
if (values.length > 0) {
return {
...acc,
[facets[machineName].filter]: [...values],
[facets[machineName as keyof typeof facets].filter]: [...values],
}
}
return acc
Expand All @@ -52,7 +51,7 @@ export const getFacetsForSearchRequest = (searchParams: ReadonlyURLSearchParams)
export const getNextPageParamsFunc = (
currentPage: number
): GetNextPageParamFunction<number, SearchWithPaginationQuery> => {
const limit = goConfig<number>("search.item.limit")
const limit = goConfig("search.item.limit")

return ({ search: { hitcount } }) => {
const totalPages = Math.ceil(hitcount / limit)
Expand Down
7 changes: 3 additions & 4 deletions components/shared/searchFilters/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.share
import { ReadonlyURLSearchParams } from "next/navigation"

import goConfig from "@/lib/config/config"
import { TConfigSearchFacets } from "@/lib/config/resolvers/search"
import { FacetFieldEnum, SearchFacetFragment } from "@/lib/graphql/generated/fbi/graphql"
import { TContext, TFilters } from "@/lib/machines/search/types"

Expand Down Expand Up @@ -44,14 +43,14 @@ export const sortByActiveFacets = (facet: SearchFacetFragment, selectedFilters:
}

export const getFacetMachineNames = () => {
const facets = goConfig<Record<string, unknown>>("search.facets")
const facets = goConfig("search.facets")
return Object.keys(facets) as FacetFieldEnum[]
}

export const getFacetTranslation = (facetFilter: keyof TFilters) => {
const facets = goConfig<TConfigSearchFacets>("search.facets")
const facets = goConfig("search.facets")

return facets[facetFilter.toUpperCase() as keyof TConfigSearchFacets].translation || ""
return facets[facetFilter.toUpperCase() as keyof typeof facets].translation || ""
}

export const getActiveFilters = (
Expand Down
11 changes: 8 additions & 3 deletions lib/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ const resolvers = {
...token,
}

const retrieveValue = (key: keyof typeof resolvers) => {
type TResolvers = typeof resolvers
type TConfigKey = keyof TResolvers

const retrieveValue = (key: TConfigKey): any => {
if (key in resolvers) {
if (typeof resolvers[key] !== "function") {
return resolvers[key]
Expand All @@ -24,8 +27,10 @@ const retrieveValue = (key: keyof typeof resolvers) => {
return null
}

const goConfig = <TValue>(key: keyof typeof resolvers) => {
const value = retrieveValue(key) as TValue
const goConfig = <K extends TConfigKey>(
key: K
): TResolvers[K] extends () => infer R ? R : TResolvers[K] => {
const value = retrieveValue(key)

if (!value && value !== 0) {
throw new MissingConfigurationError(`Missing configuration for ${key}`)
Expand Down
1 change: 1 addition & 0 deletions lib/config/resolvers/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const app = {
}
}
}
throw new Error("No app URL found.")
},
}

Expand Down
2 changes: 0 additions & 2 deletions lib/config/resolvers/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,4 @@ const search = {
},
}

export type TConfigSearchFacets = Record<FacetFieldEnum, { filter: string; translation: string }>

export default search
1 change: 1 addition & 0 deletions lib/config/resolvers/service.unilogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const serviceUnilogin = {
if (process.env.UNILOGIN_SESSION_SECRET) {
return process.env.UNILOGIN_SESSION_SECRET
}
throw new Error("No unilogin session secret found.")
},
}

Expand Down
6 changes: 3 additions & 3 deletions lib/machines/search/useSearchMachineActor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import searchMachine from "./search.machine"

const searchActor = createActor(searchMachine, {
input: {
initialOffset: goConfig<number>("search.offset.initial"),
searchPageSize: goConfig<number>("search.item.limit"),
facetLimit: goConfig<number>("search.facet.limit"),
initialOffset: goConfig("search.offset.initial"),
searchPageSize: goConfig("search.item.limit"),
facetLimit: goConfig("search.facet.limit"),
},
}).start()

Expand Down
10 changes: 5 additions & 5 deletions lib/session/oauth/uniloginClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import { Issuer } from "openid-client"
import goConfig from "@/lib/config/config"

export const getOpenIdClientUniloginClientConfig = async () => {
const appUrl = await goConfig<Promise<string | undefined>>("app.url")
const apiUrl = await goConfig<Promise<string | undefined>>("service.unilogin.api.url")
const appUrl = goConfig("app.url")
const apiUrl = await goConfig("service.unilogin.api.url")

return {
wellKnownUrl: await goConfig<Promise<string | undefined>>("service.unilogin.wellknown.url"),
wellKnownUrl: await goConfig("service.unilogin.wellknown.url"),
url: apiUrl,
audience: apiUrl,
client_id: await goConfig<Promise<string | undefined>>("service.unilogin.client-id"),
client_secret: await goConfig<Promise<string | undefined>>("service.unilogin.client-secret"),
client_id: await goConfig("service.unilogin.client-id"),
client_secret: await goConfig("service.unilogin.client-secret"),
scope: "openid",
redirect_uri: `${appUrl}/auth/callback/unilogin`,
post_logout_redirect_uri: appUrl,
Expand Down

0 comments on commit 2f75108

Please sign in to comment.