Skip to content

Commit

Permalink
Merge branch 'dev' into IN-857-user-management
Browse files Browse the repository at this point in the history
  • Loading branch information
kodiakhq[bot] committed May 3, 2024
2 parents 81ff8cb + 49c15fe commit a9230db
Show file tree
Hide file tree
Showing 12 changed files with 171 additions and 181 deletions.
2 changes: 0 additions & 2 deletions apps/app/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -352,11 +352,9 @@ export const getStaticProps: GetStaticProps = async ({ locale }) => {
ssg.review.getFeatured.prefetch(3),
])

// await ssg.review.getFeatured.prefetch(3)
return {
props: {
trpcState: ssg.dehydrate(),
// ...(await getServerSideTranslations(locale, ['common', 'landingPage', 'attribute'])),
...(i18n.status === 'fulfilled' ? i18n.value : {}),
},
revalidate: 60 * 60 * 24, // 24 hours
Expand Down
12 changes: 5 additions & 7 deletions apps/app/src/pages/org/[slug]/[orgLocationId]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { type InferGetServerSidePropsType, type NextPage } from 'next'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
import { type GetServerSidePropsContext } from 'nextjs-routes'
import { type GetServerSideProps } from 'nextjs-routes'
import { useCallback, useEffect, useRef, useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { z } from 'zod'
Expand Down Expand Up @@ -239,12 +239,10 @@ const OrgLocationPage: NextPage<InferGetServerSidePropsType<typeof getServerSide
)
}

export const getServerSideProps = async ({
locale,
params,
req,
res,
}: GetServerSidePropsContext<'/org/[slug]/[orgLocationId]/edit'>) => {
export const getServerSideProps: GetServerSideProps<
{ organizationId: string } & Record<string, unknown>,
'/org/[slug]/[orgLocationId]/edit'
> = async ({ locale, params, req, res }) => {
const urlParams = z.object({ slug: z.string(), orgLocationId: prefixedId('orgLocation') }).safeParse(params)
if (!urlParams.success) {
return { notFound: true }
Expand Down
13 changes: 6 additions & 7 deletions apps/app/src/pages/org/[slug]/[orgLocationId]/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createStyles, Divider, Grid, Stack, Tabs, useMantineTheme } from '@mantine/core'
import { useMediaQuery } from '@mantine/hooks'
// import compact from 'just-compact'
import { type GetStaticPaths, type GetStaticPropsContext, type NextPage } from 'next'
import { type GetStaticPaths, type GetStaticProps, type NextPage } from 'next'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'
Expand Down Expand Up @@ -178,10 +178,10 @@ export const getStaticPaths: GetStaticPaths = async () => {
fallback: true,
}
}
export const getStaticProps = async ({
locale,
params,
}: GetStaticPropsContext<RoutedQuery<'/org/[slug]/[orgLocationId]'>>) => {
export const getStaticProps: GetStaticProps<
Record<string, unknown>,
RoutedQuery<'/org/[slug]/[orgLocationId]'>
> = async ({ locale, params }) => {
const urlParams = z.object({ slug: z.string(), orgLocationId: z.string() }).safeParse(params)
if (!urlParams.success) {
return { notFound: true }
Expand Down Expand Up @@ -213,7 +213,6 @@ export const getStaticProps = async ({
])
const props = {
trpcState: ssg.dehydrate(),
// ...(await getServerSideTranslations(locale, ['common', 'services', 'attribute', 'phone-type', slug])),
...(i18n.status === 'fulfilled' ? i18n.value : {}),
}

Expand All @@ -226,7 +225,7 @@ export const getStaticProps = async ({
if (error instanceof TRPCError && error.code === 'NOT_FOUND') {
return { notFound: true }
}
return { props: {}, revalidate: 1 }
return { redirect: { destination: '/500', permanent: false } }
}
}
type Tabname = 'services' | 'photos' | 'reviews'
Expand Down
8 changes: 4 additions & 4 deletions apps/app/src/pages/org/[slug]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { Grid, Stack } from '@mantine/core'
import { useElementSize } from '@mantine/hooks'
import { t } from 'i18next'
import compact from 'just-compact'
import { type GetServerSidePropsContext, type InferGetServerSidePropsType } from 'next'
import { type InferGetServerSidePropsType } from 'next'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { type RoutedQuery } from 'nextjs-routes'
import { type GetServerSideProps } from 'nextjs-routes'
import { useEffect, useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { z } from 'zod'
Expand Down Expand Up @@ -136,12 +136,12 @@ const OrganizationPage: NextPageWithOptions<InferGetServerSidePropsType<typeof g
)
}

export const getServerSideProps = async ({
export const getServerSideProps: GetServerSideProps<{ organizationId: string }, '/org/[slug]'> = async ({
locale,
params,
req,
res,
}: GetServerSidePropsContext<RoutedQuery<'/org/[slug]'>>) => {
}) => {
if (!params) {
return { notFound: true }
}
Expand Down
12 changes: 7 additions & 5 deletions apps/app/src/pages/org/[slug]/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createStyles, Divider, Grid, Stack, Tabs, useMantineTheme } from '@mantine/core'
import { useElementSize, useMediaQuery } from '@mantine/hooks'
import { type GetStaticPaths, type GetStaticPropsContext, type InferGetStaticPropsType } from 'next'
import { type GetStaticPaths, type GetStaticProps, type InferGetStaticPropsType } from 'next'
import dynamic from 'next/dynamic'
import Head from 'next/head'
import { useRouter } from 'next/router'
Expand Down Expand Up @@ -245,10 +245,10 @@ export const getStaticPaths: GetStaticPaths = async () => {
// }
}

export const getStaticProps = async ({
locale,
params,
}: GetStaticPropsContext<RoutedQuery<'/org/[slug]'>>) => {
export const getStaticProps: GetStaticProps<
{ slug: string; organizationId: string },
RoutedQuery<'/org/[slug]'>
> = async ({ locale, params }) => {
if (!params) {
return { notFound: true }
}
Expand Down Expand Up @@ -290,6 +290,8 @@ export const getStaticProps = async ({
const TRPCError = (await import('@trpc/server')).TRPCError
if (error instanceof TRPCError && error.code === 'NOT_FOUND') {
return { notFound: true }
} else {
return { redirect: { destination: '/500', permanent: false } }
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions apps/app/src/pages/search/intl/[country].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
useMantineTheme,
} from '@mantine/core'
import { useMediaQuery } from '@mantine/hooks'
import { type GetStaticPaths, type GetStaticPropsContext } from 'next'
import { type GetStaticPaths, type GetStaticProps } from 'next'
import dynamic from 'next/dynamic'
import Head from 'next/head'
import { useRouter } from 'next/router'
Expand Down Expand Up @@ -152,10 +152,10 @@ export const getStaticPaths: GetStaticPaths = async () => {
fallback: 'blocking',
}
}
export const getStaticProps = async ({
params,
locale,
}: GetStaticPropsContext<RoutedQuery<'/search/intl/[country]'>>) => {
export const getStaticProps: GetStaticProps<
Record<string, unknown>,
RoutedQuery<'/search/intl/[country]'>
> = async ({ params, locale }) => {
const parsedQuery = QuerySchema.safeParse(params)
if (!parsedQuery.success) {
return {
Expand Down
5 changes: 2 additions & 3 deletions apps/app/src/pages/suggest.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { Grid, Overlay } from '@mantine/core'
import { type GetStaticPropsContext } from 'next'
import { type GetStaticProps } from 'next'
import dynamic from 'next/dynamic'
import { useSession } from 'next-auth/react'
import { useCallback, useState } from 'react'

import { trpcServerClient } from '@weareinreach/api/trpc'
import { SuggestOrg } from '@weareinreach/ui/components/sections/SuggestOrg'
import { getServerSideTranslations } from '~app/utils/i18n'
// import { QuickPromotionModal } from '@weareinreach/ui/modals'

// @ts-expect-error Next Dynamic doesn't like polymorphic components
const QuickPromotionModal = dynamic(() =>
Expand Down Expand Up @@ -37,7 +36,7 @@ const SuggestResource = () => {

export default SuggestResource

export const getStaticProps = async ({ locale }: GetStaticPropsContext) => {
export const getStaticProps: GetStaticProps = async ({ locale }) => {
const ssg = await trpcServerClient({ session: null })

const [i18n] = await Promise.allSettled([
Expand Down
18 changes: 7 additions & 11 deletions packages/api/lib/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { TRPCError } from '@trpc/server'
// import { Logger } from 'tslog'
import { ZodError } from 'zod'

import { Prisma } from '@weareinreach/db'
import { createLoggerInstance } from '@weareinreach/util/logger'

import { PRISMA_ERROR_CODES } from './prismaErrorCodes'

Expand All @@ -12,17 +12,11 @@ const mapEntries = Object.entries(PRISMA_ERROR_CODES).map(([key, value]) => [key
][]
const prismaErrorMap = new Map<string, TRPCError['code']>(mapEntries)

// const devLog = (error: unknown) => {
// // eslint-disable-next-line node/no-process-env
// if (process.env.NODE_ENV !== 'production') {
// const logger = new Logger()

// logger.error(error)
// }
// }
const logger = createLoggerInstance('tRPC Error Handler')

export const handleError = (error: unknown) => {
// devLog(error)
logger.error(error)

// pass through if already TRPCError
if (error instanceof TRPCError) {
throw error
Expand All @@ -44,7 +38,9 @@ export const handleError = (error: unknown) => {
if (error instanceof Error) {
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: error.message, cause: error.cause })
} else {
if (typeof error === 'object') error = JSON.stringify(error)
if (typeof error === 'object') {
error = JSON.stringify(error)
}
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: `${error}` })
}
}
81 changes: 43 additions & 38 deletions packages/api/router/organization/query.forOrgPage.handler.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,56 @@
import { prisma } from '@weareinreach/db'
import { handleError } from '~api/lib/errorHandler'
import { attributes, freeText, isPublic } from '~api/schemas/selects/common'
import { type TRPCHandlerParams } from '~api/types/handler'

import { type TForOrgPageSchema } from './query.forOrgPage.schema'

const forOrgPage = async ({ input }: TRPCHandlerParams<TForOrgPageSchema>) => {
const { slug } = input
const org = await prisma.organization.findUniqueOrThrow({
where: {
slug,
...isPublic,
},
select: {
id: true,
name: true,
slug: true,
published: true,
lastVerified: true,
allowedEditors: { where: { authorized: true }, select: { userId: true } },
description: freeText,

reviews: {
where: { visible: true, deleted: false },
select: { id: true },
try {
const { slug } = input
const org = await prisma.organization.findUniqueOrThrow({
where: {
slug,
...isPublic,
},
locations: {
where: isPublic,
select: {
id: true,
street1: true,
street2: true,
city: true,
postCode: true,
country: { select: { cca2: true } },
govDist: { select: { abbrev: true, tsKey: true, tsNs: true } },
notVisitable: true,
select: {
id: true,
name: true,
slug: true,
published: true,
lastVerified: true,
allowedEditors: { where: { authorized: true }, select: { userId: true } },
description: freeText,

reviews: {
where: { visible: true, deleted: false },
select: { id: true },
},
locations: {
where: isPublic,
select: {
id: true,
street1: true,
street2: true,
city: true,
postCode: true,
country: { select: { cca2: true } },
govDist: { select: { abbrev: true, tsKey: true, tsNs: true } },
notVisitable: true,
},
},
attributes,
},
attributes,
},
})
const { allowedEditors, ...orgData } = org
const reformatted = {
...orgData,
isClaimed: Boolean(allowedEditors.length),
}
})
const { allowedEditors, ...orgData } = org
const reformatted = {
...orgData,
isClaimed: Boolean(allowedEditors.length),
}

return reformatted
return reformatted
} catch (err) {
return handleError(err)
}
}
export default forOrgPage
41 changes: 23 additions & 18 deletions packages/api/router/organization/query.getIdFromSlug.handler.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
import { checkPermissions } from '@weareinreach/auth'
import { prisma } from '@weareinreach/db'
import { readSlugCache, writeSlugCache } from '~api/cache/slugToOrgId'
import { handleError } from '~api/lib/errorHandler'
import { isPublic } from '~api/schemas/selects/common'
import { type TRPCHandlerParams } from '~api/types/handler'

import { type TGetIdFromSlugSchema } from './query.getIdFromSlug.schema'

const getIdFromSlug = async ({ ctx, input }: TRPCHandlerParams<TGetIdFromSlugSchema>) => {
const { slug } = input
const cachedId = await readSlugCache(slug)
if (cachedId) {
return { id: cachedId }
}
const canSeeUnpublished =
ctx.session !== null &&
checkPermissions({
session: ctx.session,
permissions: ['dataPortalBasic', 'dataPortalAdmin', 'dataPortalManager'],
has: 'some',
try {
const { slug } = input
const cachedId = await readSlugCache(slug)
if (cachedId) {
return { id: cachedId }
}
const canSeeUnpublished =
ctx.session !== null &&
checkPermissions({
session: ctx.session,
permissions: ['dataPortalBasic', 'dataPortalAdmin', 'dataPortalManager'],
has: 'some',
})
const orgId = await prisma.organization.findUniqueOrThrow({
where: { slug, ...(canSeeUnpublished ? {} : isPublic) },
select: { id: true, published: true, deleted: true },
})
const orgId = await prisma.organization.findUniqueOrThrow({
where: { slug, ...(canSeeUnpublished ? {} : isPublic) },
select: { id: true, published: true, deleted: true },
})
if (orgId.published && !orgId.deleted) {
await writeSlugCache(slug, orgId.id)
if (orgId.published && !orgId.deleted) {
await writeSlugCache(slug, orgId.id)
}
return { id: orgId.id }
} catch (err) {
return handleError(err)
}
return { id: orgId.id }
}
export default getIdFromSlug

0 comments on commit a9230db

Please sign in to comment.