Skip to content

Commit

Permalink
feat: route for reset the jobs cache (#331)
Browse files Browse the repository at this point in the history
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
Luisfp0 and github-actions[bot] authored Oct 9, 2024
1 parent 8a49e5b commit 6845d85
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 15 deletions.
2 changes: 1 addition & 1 deletion apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ CRON_SECRET=
NEXT_PUBLIC_PLAUSIBLE_ADDRESS=

REDIS_HOST=
REDIS_PORT=
REDIS_PORT=
30 changes: 18 additions & 12 deletions apps/web/app/(roles)/vagas/page.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,47 @@
'use server'

import { getSupabaseClient } from 'db'
import { Database, getSupabaseClient } from 'db'
import { RolesPage } from './RolesPage'
import { fetchJobs } from './action'
import getRedisClient from 'app/utils/getRedisClient'

const ONE_DAY_IN_MINUTES = 86_400

async function getJobs() {
type Job = Database['public']['Tables']['Roles']['Row']
type Skill = Database['public']['Views']['vw_skills_in_roles']['Row']
type Country = Database['public']['Views']['vw_countries_in_roles']['Row']

async function getJobs(): Promise<Job[]> {
try {
const client = await getRedisClient()
const jobsFromCache = await client.get('web_jobs')
// if (jobsFromCache) {
// await client.quit()
// return JSON.parse(jobsFromCache)
// }
if (jobsFromCache) {
await client.quit()
console.log('cache')
return JSON.parse(jobsFromCache) as Job[]
}

const { data: jobs } = await fetchJobs([])
console.log('supabase')

await client.set('web_jobs', JSON.stringify(jobs), {
EX: ONE_DAY_IN_MINUTES,
})
await client.quit()
return jobs
return jobs as Job[]
} catch (error) {
console.error('Failed to fetch jobs:', error)
return []
}
}

async function getSkills() {
async function getSkills(): Promise<Skill[]> {
try {
const client = await getRedisClient()
const skillsFromCache = await client.get('Skills')
if (skillsFromCache) {
await client.quit()
return JSON.parse(skillsFromCache)
return JSON.parse(skillsFromCache) as Skill[]
}

const supabase = getSupabaseClient()
Expand All @@ -48,21 +54,21 @@ async function getSkills() {
EX: ONE_DAY_IN_MINUTES,
})
await client.quit()
return skills
return skills as Skill[]
} catch (error) {
console.error('Failed to fetch skills:', error)
return []
}
}

async function getCountries() {
async function getCountries(): Promise<Country[]> {
try {
const supabase = getSupabaseClient()
const { data: countries } = await supabase
.from('vw_countries_in_roles')
.select('*')
.order('country')
return countries
return countries as Country[]
} catch (error) {
console.error('Failed to fetch countries:', error)
return []
Expand Down
57 changes: 57 additions & 0 deletions apps/web/app/api/resetJobsCache/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Jobs Cache Reset Endpoint

This endpoint allows resetting and repopulating the jobs cache in Redis.

## Endpoint

`GET /api/resetJobsCache`

## Purpose

To clear the existing jobs cache and repopulate it with up-to-date data from the database. This is useful when significant changes have been made to the data and you need these changes to be reflected immediately, without waiting for the natural expiration of the cache.

## How to Use

1. Make a GET request to `/api/resetJobsCache` with the authentication token.
2. The endpoint will delete the existing cache, fetch new data from the database, and store it in Redis.

## Parameters

- `token` (required): Authentication token to access the endpoint.

Example usage:

```
https://www.trampardecasa.com.br/api/resetJobsCache?token=SECRET_KEY
```

## Response

- Success (200 OK):

```json
{
"message": "Cache reset and refilled successfully"
}
```

- Error (401 Unauthorized):

```json
{
"error": "Unauthorized"
}
```

- Error (500 Internal Server Error):
```json
{
"error": "Failed to reset and refill cache"
}
```

## Environment Variables

Ensure the following environment variable is set:

- `SECRET_KEY`: The secret token for authenticating reset requests.
37 changes: 37 additions & 0 deletions apps/web/app/api/resetJobsCache/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server'
import getRedisClient from 'app/utils/getRedisClient'
import { fetchJobs } from 'app/(roles)/vagas/action'

const ONE_DAY_IN_MINUTES = 86_400

export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const token = searchParams.get('token')
if (token !== process.env.SECRET_KEY) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

try {
const client = await getRedisClient()

await client.del('web_jobs')

const { data: fetchedJobs } = await fetchJobs([])

await client.set('web_jobs', JSON.stringify(fetchedJobs), {
EX: ONE_DAY_IN_MINUTES,
})

await client.quit()

return NextResponse.json({
message: 'Cache reset and refilled successfully',
})
} catch (error) {
console.error('Failed to reset and refill cache:', error)
return NextResponse.json(
{ error: 'Failed to reset and refill cache' },
{ status: 500 }
)
}
}
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "web",
"version": "1.0.40",
"version": "1.0.41",
"private": true,
"scripts": {
"dev": "development=true next dev",
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10136,7 +10136,7 @@ web-streams-polyfill@^3.0.3:
integrity sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==

"web@file:/home/runner/work/trampar-de-casa/trampar-de-casa/apps/web":
version "1.0.40"
version "1.0.41"
resolved "file:apps/web"
dependencies:
"@headlessui/react" "^1.7.15"
Expand Down

0 comments on commit 6845d85

Please sign in to comment.