Skip to content

Commit

Permalink
feat: added cron job and a service to update/retrieve Trustpilot data
Browse files Browse the repository at this point in the history
  • Loading branch information
guilhermespopolin committed Jul 7, 2023
1 parent f411945 commit 917f0bf
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 1 deletion.
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
HEDVIG_BUSINESS_UNIT_ID=
TRUSTPILOT_API_KEY=

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

NEXT_PUBLIC_EXPERIMENT_ID=<experiment-id>
Expand Down
94 changes: 94 additions & 0 deletions apps/store/src/pages/api/cron/trustpilot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { NextResponse } from 'next/server'
import { type TrustpilotData, EDGE_CONFIG_STORE_KEY } from '@/services/trustpilot/trustpilot.types'

export const config = {
runtime: 'edge',
}

const handler = async () => {
try {
const data = await fetchTrustpilotData()
await persistTrustpilotData(data)
return new NextResponse(null, { status: 200 })
} catch (error) {
console.error(error)
return new NextResponse(JSON.stringify({ error }), { status: 500 })
}
}

export default handler

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

async function fetchTrustpilotData(): Promise<TrustpilotData> {
const hedvigBusinessUnitId = process.env.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,
}
}

async function persistTrustpilotData(value: TrustpilotData) {
const manageApiUrl = process.env.EDGE_CONFIG_MANAGE_API_URL
if (!manageApiUrl) {
throw new Error('EDGE_CONFIG_MANAGE_API_URL not configured')
}

const manageApiToken = process.env.EDGE_CONFIG_MANAGE_API_TOKEN
if (!manageApiToken) {
throw new Error('EDGE_CONFIG_MANAGE_API_TOKEN not configured')
}

const response = await fetch(manageApiUrl, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${manageApiToken}`,
'Content-type': 'application/json',
},
body: JSON.stringify({
items: [
{
operation: 'upsert',
key: EDGE_CONFIG_STORE_KEY,
value: value,
},
],
}),
})

if (response.ok) {
console.log('Trustpilot info updated in Edge config')
} else {
throw new Error(`Failed to update Trustpilot info in Edge config: ${response.statusText}`)
}
}
24 changes: 24 additions & 0 deletions apps/store/src/services/trustpilot/trustpilot.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { get as getFromConfig } from '@vercel/edge-config'
import { atom, useAtomValue } from 'jotai'
import { useHydrateAtoms } from 'jotai/utils'
import { type TrustpilotData, EDGE_CONFIG_STORE_KEY } from './trustpilot.types'

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

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

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

export const fetchTrustpilotData = async () => {
const data = await getFromConfig<TrustpilotData>(EDGE_CONFIG_STORE_KEY)

if (!data) {
throw new Error('Failed to retrieve Trustpilot data from edge config')
}

return data
}
6 changes: 6 additions & 0 deletions apps/store/src/services/trustpilot/trustpilot.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const EDGE_CONFIG_STORE_KEY = 'trustpilot'

export type TrustpilotData = {
score: number
totalReviews: number
}
8 changes: 7 additions & 1 deletion apps/store/vercel.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,11 @@
"regions": ["arn1"],
"github": {
"autoJobCancelation": true
}
},
"crons": [
{
"path": "/api/cron/trustpilot",
"schedule": "0 8 * * 1"
}
]
}

0 comments on commit 917f0bf

Please sign in to comment.