2024-02-01 18:10:15 -05:00
|
|
|
import { Connections } from '$lib/server/users'
|
2024-01-31 12:19:57 -05:00
|
|
|
import { isValidURL } from '$lib/utils'
|
2024-01-30 12:27:37 -05:00
|
|
|
import type { RequestHandler } from '@sveltejs/kit'
|
|
|
|
|
import { z } from 'zod'
|
|
|
|
|
|
|
|
|
|
export const GET: RequestHandler = async ({ params }) => {
|
|
|
|
|
const userId = params.userId as string
|
|
|
|
|
|
|
|
|
|
const connections = Connections.getUserConnections(userId)
|
2024-01-31 01:17:24 -05:00
|
|
|
return new Response(JSON.stringify(connections))
|
2024-01-30 12:27:37 -05:00
|
|
|
}
|
|
|
|
|
|
2024-01-31 12:19:57 -05:00
|
|
|
const connectionSchema = z.object({
|
|
|
|
|
serviceType: z.enum(['jellyfin', 'youtube-music']),
|
|
|
|
|
serviceUserId: z.string(),
|
2024-02-01 18:10:15 -05:00
|
|
|
urlOrigin: z.string().refine((val) => isValidURL(val)),
|
2024-01-31 12:19:57 -05:00
|
|
|
accessToken: z.string(),
|
|
|
|
|
})
|
|
|
|
|
export type NewConnection = z.infer<typeof connectionSchema>
|
|
|
|
|
|
|
|
|
|
export const POST: RequestHandler = async ({ params, request }) => {
|
2024-01-30 12:27:37 -05:00
|
|
|
const userId = params.userId as string
|
|
|
|
|
|
2024-01-31 01:17:24 -05:00
|
|
|
const connection = await request.json()
|
|
|
|
|
|
|
|
|
|
const connectionValidation = connectionSchema.safeParse(connection)
|
|
|
|
|
if (!connectionValidation.success) return new Response(connectionValidation.error.message, { status: 400 })
|
|
|
|
|
|
2024-02-01 18:10:15 -05:00
|
|
|
const { serviceType, serviceUserId, urlOrigin, accessToken } = connectionValidation.data
|
|
|
|
|
const service: Service = {
|
|
|
|
|
type: serviceType,
|
|
|
|
|
userId: serviceUserId,
|
|
|
|
|
urlOrigin: new URL(urlOrigin).origin,
|
|
|
|
|
}
|
|
|
|
|
const newConnection = Connections.addConnection(userId, service, accessToken)
|
2024-01-31 01:17:24 -05:00
|
|
|
return new Response(JSON.stringify(newConnection))
|
|
|
|
|
}
|
2024-01-30 12:27:37 -05:00
|
|
|
|
2024-01-31 01:17:24 -05:00
|
|
|
export const DELETE: RequestHandler = async ({ request }) => {
|
|
|
|
|
const connectionId: string = await request.json()
|
|
|
|
|
try {
|
|
|
|
|
Connections.deleteConnection(connectionId)
|
|
|
|
|
return new Response('Connection Deleted')
|
|
|
|
|
} catch {
|
|
|
|
|
return new Response('Connection does not exist', { status: 400 })
|
|
|
|
|
}
|
2024-01-30 12:27:37 -05:00
|
|
|
}
|