Skip to content

Commit

Permalink
feat: added trustpilot service to retrieve Trustpilot data
Browse files Browse the repository at this point in the history
  • Loading branch information
guilhermespopolin committed Jul 7, 2023
1 parent 8c1afa9 commit a2115a8
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
4 changes: 4 additions & 0 deletions apps/store/.env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ EDGE_CONFIG=
EDGE_CONFIG_MANAGE_API_URL=https://api.vercel.com/v1/edge-config/:configId/items?teamId=:teamId
EDGE_CONFIG_MANAGE_API_TOKEN=:token

# Trustpilot
TRUSTPILOT_HEDVIG_BUSINESS_UNIT_ID=
TRUSTPILOT_API_KEY=

FALLBACK_ORIGIN_URL=https://www.dev.hedvigit.com

NEXT_PUBLIC_EXPERIMENT_ID=<experiment-id>
Expand Down
59 changes: 59 additions & 0 deletions apps/store/src/services/trustpilot/trustpilot.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { atom, useAtomValue } from 'jotai'
import { useHydrateAtoms } from 'jotai/utils'
import { type TrustpilotData } from './trustpilot.types'

type JSONResponse = {
score: {
trustScore: number
}
numberOfReviews: {
total: number
}
}

const trustpilotAtom = atom<TrustpilotData | null>(null)

export const useTrustpilotData = () => {
return useAtomValue(trustpilotAtom)
}

export const useHydrateTrustpilotData = (data: TrustpilotData | null) => {
useHydrateAtoms([[trustpilotAtom, data] as const])
}

export const fetchTrustpilotData = async () => {
try {
const hedvigBusinessUnitId = process.env.TRUSTPILOT_HEDVIG_BUSINESS_UNIT_ID
if (!hedvigBusinessUnitId) {
throw new Error('HEDVIG_BUSINESS_UNIT_ID is not configured')
}

const trustpilotApiKey = process.env.TRUSTPILOT_API_KEY
if (!trustpilotApiKey) {
throw new Error('`TRUSTPILOT_API_KEY` is not configured')
}

const response = await fetch(
`https://api.trustpilot.com/v1/business-units/${hedvigBusinessUnitId}`,
{
headers: {
apiKey: trustpilotApiKey,
},
},
)

if (!response.ok) {
throw new Error(`Failed to retrieve Trustpilot information: ${response.statusText}`)
}

const { score, numberOfReviews }: JSONResponse = await response.json()

return {
score: score.trustScore,
totalReviews: numberOfReviews.total,
}
} catch (error) {
console.error(error)
return null
}
}
4 changes: 4 additions & 0 deletions apps/store/src/services/trustpilot/trustpilot.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type TrustpilotData = {
score: number
totalReviews: number
}

0 comments on commit a2115a8

Please sign in to comment.