Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Improve Lesson Upsert to Typesense #347

Merged
merged 2 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion apps/egghead/src/lib/egghead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ export async function updateEggheadLesson(input: {
duration: number
hlsUrl?: string
body?: string
published_at?: string
}) {
const {
eggheadLessonId,
Expand All @@ -158,6 +159,7 @@ export async function updateEggheadLesson(input: {
slug,
guid,
body = '',
published_at = null,
} = input
await eggheadPgQuery(
`UPDATE lessons SET
Expand All @@ -171,7 +173,8 @@ export async function updateEggheadLesson(input: {
guid = $7,
summary = $8,
is_pro_content = $10,
free_forever = NOT $10
free_forever = NOT $10,
published_at = $11
WHERE id = $9`,
[
state,
Expand All @@ -184,6 +187,7 @@ export async function updateEggheadLesson(input: {
body,
eggheadLessonId,
access,
published_at,
],
)
}
Expand Down Expand Up @@ -266,6 +270,10 @@ export const eggheadLessonSchema = z.object({
state: z.string(),
instructor: z.object({
id: z.number(),
name: z.string(),
url: z.string().url(),
avatar_url: z.string().url(),
avatar_file_name: z.string(),
}),
})

Expand Down
5 changes: 4 additions & 1 deletion apps/egghead/src/lib/posts-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import {
updateSanityLesson,
} from './sanity-content-query'
import { EggheadTag, EggheadTagSchema } from './tags'
import { upsertPostToTypeSense } from './typesense'
import { upsertPostToTypeSense } from './typesense-query'

export async function searchLessons(searchTerm: string) {
const { session } = await getServerAuthSession()
Expand Down Expand Up @@ -517,6 +517,9 @@ export async function writePostUpdateToDatabase(input: {
...(videoResource?.muxPlaybackId && {
hlsUrl: `https://stream.mux.com/${videoResource.muxPlaybackId}.m3u8`,
}),
...(action === 'publish' && {
published_at: new Date().toISOString(),
}),
})
}

Expand Down
94 changes: 94 additions & 0 deletions apps/egghead/src/lib/typesense-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import Typesense from 'typesense'

import { getEggheadLesson } from './egghead'
import { Post, PostAction } from './posts'
import { getPostTags } from './posts-query'
import { InstructorSchema, TypesensePostSchema } from './typesense'

export async function upsertPostToTypeSense(post: Post, action: PostAction) {
let client = new Typesense.Client({
nodes: [
{
host: process.env.NEXT_PUBLIC_TYPESENSE_HOST!,
port: 443,
protocol: 'https',
},
],
apiKey: process.env.TYPESENSE_WRITE_API_KEY!,
connectionTimeoutSeconds: 2,
})

const shouldIndex =
post.fields.state === 'published' && post.fields.visibility === 'public'

if (!shouldIndex) {
await client
.collections(process.env.TYPESENSE_COLLECTION_NAME!)
.documents(String(post.fields.eggheadLessonId))
.delete()
.catch((err) => {
console.error(err)
})
} else {
if (!post.fields.eggheadLessonId) {
return
}

const lesson = await getEggheadLesson(post.fields.eggheadLessonId)

console.log('lesson', lesson)

const instructor = InstructorSchema.parse({
id: lesson.instructor?.id,
name: lesson.instructor?.full_name,
first_name: lesson.instructor?.first_name,
last_name: lesson.instructor?.last_name,
url: lesson.instructor?.url,
avatar_url: lesson.instructor?.avatar_url,
})

const tags = await getPostTags(post.id)

const resource = TypesensePostSchema.safeParse({
id: `${post.fields.eggheadLessonId}`,
externalId: post.id,
title: post.fields.title,
slug: post.fields.slug,
summary: post.fields.description,
description: post.fields.body,
name: post.fields.title,
path: `/${post.fields.slug}`,
type: post.fields.postType,
_tags: tags.map((tag) => tag.fields.name),
...(lesson && {
instructor_name: lesson.instructor?.full_name,
instructor,
image: lesson.image_480_url,
published_at_timestamp: lesson.published_at
? new Date(lesson.published_at).getTime()
: null,
}),
})

if (!resource.success) {
console.error(resource.error)
return
}

console.log('resource', resource.data)

await client
.collections(process.env.TYPESENSE_COLLECTION_NAME!)
.documents()
.upsert({
...resource.data,
...(action === 'publish' && {
published_at_timestamp: post.updatedAt?.getTime() ?? Date.now(),
}),
updated_at_timestamp: post.updatedAt?.getTime() ?? Date.now(),
})
.catch((err) => {
console.error(err)
})
}
}
89 changes: 27 additions & 62 deletions apps/egghead/src/lib/typesense.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,30 @@
import Typesense from 'typesense'
import * as z from 'zod'

import { getEggheadLesson } from './egghead'
import { Post, PostAction } from './posts'
export const InstructorSchema = z.object({
id: z.number().optional(),
name: z.string().optional(),
first_name: z.string().optional(),
last_name: z.string().optional(),
full_name: z.string().optional(),
avatar_url: z.string().url().optional(),
})

export async function upsertPostToTypeSense(post: Post, action: PostAction) {
let client = new Typesense.Client({
nodes: [
{
host: process.env.NEXT_PUBLIC_TYPESENSE_HOST!,
port: 443,
protocol: 'https',
},
],
apiKey: process.env.TYPESENSE_WRITE_API_KEY!,
connectionTimeoutSeconds: 2,
})
export const TypesensePostSchema = z.object({
type: z.string().optional(),
id: z.string().optional(),
name: z.string().optional(),
title: z.string().optional(),
slug: z.string().optional(),
externalId: z.string().optional(),
description: z.string().optional(),
summary: z.string().optional(),
image: z.string().optional(),
_tags: z.array(z.string()).optional(),
instructor: InstructorSchema.optional(),
instructor_name: z.string().optional(),
instructor_url: z.string().url().optional(),
path: z.string().optional(),
published_at_timestamp: z.number().nullish(),
})

const shouldIndex =
post.fields.state === 'published' && post.fields.visibility === 'public'

if (!shouldIndex) {
await client
.collections(process.env.TYPESENSE_COLLECTION_NAME!)
.documents(String(post.fields.eggheadLessonId))
.delete()
.catch((err) => {
console.error(err)
})
} else {
if (!post.fields.eggheadLessonId) {
return
}
const lesson = await getEggheadLesson(post.fields.eggheadLessonId)
const resource = {
id: `${post.fields.eggheadLessonId}`,
externalId: post.id,
title: post.fields.title,
slug: post.fields.slug,
summary: post.fields.description,
description: post.fields.body,
name: post.fields.title,
path: `/${post.fields.slug}`,
type: post.fields.postType,
...(lesson && {
instructor_name: lesson.instructor?.full_name,
instructor: lesson.instructor,
image: lesson.image_480_url,
}),
}
await client
.collections(process.env.TYPESENSE_COLLECTION_NAME!)
.documents()
.upsert({
...resource,
...(action === 'publish' && {
published_at_timestamp: post.updatedAt?.getTime() ?? Date.now(),
}),
updated_at_timestamp: post.updatedAt?.getTime() ?? Date.now(),
})
.catch((err) => {
console.error(err)
})
}
}
export type TypesensePost = z.infer<typeof TypesensePostSchema>
Loading