Add loading indicator to group switcher

This commit is contained in:
VityaSchel
2023-10-15 00:58:12 +04:00
parent 95f1b8914f
commit 7e440c9bff
7 changed files with 194 additions and 30 deletions

View File

@@ -0,0 +1,64 @@
import { Day } from '@/shared/model/day'
import { parsePage } from '@/app/parser/schedule'
import contentTypeParser from 'content-type'
import { JSDOM } from 'jsdom'
// import { content as mockContent } from './mock'
import { reportParserError } from '@/app/logger'
// import { groups } from '@/shared/data/groups'
// const fetchingGroups: {
// [groupID: number]: boolean
// } = Object.fromEntries(Object.values(groups).map(([gId]) => [gId, false]))
// const callbacks: {
// [groupID: number]: Set<{ resolve: (days: Day[]) => void, reject: (e: unknown) => void }>
// } = Object.fromEntries(Object.values(groups).map(([gId]) => [gId, new Set()]))
export async function getSchedule(groupID: number, groupName: string): Promise<Day[]> {
// if (fetchingGroups[groupID]) {
// return new Promise((resolve, reject) => {
// callbacks[groupID].add({
// resolve: (days: Day[]) => resolve(days),
// reject
// })
// })
// } else {
// fetchingGroups[groupID] = true
// }
// try {
// const result = await parseSchedule(groupID, groupName)
// fetchingGroups[groupID] = false
// Array.from(callbacks[groupID].values()).forEach(({ resolve }) => resolve(result))
// callbacks[groupID].clear()
// return result
// } catch(e) {
// fetchingGroups[groupID] = false
// console.log(Array.from(callbacks[groupID].values()).length)
// Array.from(callbacks[groupID].values()).forEach(({ reject }) => reject(e))
// callbacks[groupID].clear()
// throw e
// }
}
export async function parseSchedule(groupID: number, groupName: string) {
const page = await fetch(`${process.env.PROXY_URL ?? 'https://lk.ks.psuti.ru'}/?mn=2&obj=${groupID}`)
// const page = { text: async () => mockContent, status: 200, headers: { get: (s: string) => s && 'text/html' } }
const content = await page.text()
const contentType = page.headers.get('content-type')
if (page.status === 200 && contentType && contentTypeParser.parse(contentType).type === 'text/html') {
try {
const root = new JSDOM(content).window.document
return parsePage(root, groupName)
} catch (e) {
console.error('Error while parsing lk.ks.psuti.ru')
reportParserError(new Date().toISOString(), 'Не удалось сделать парсинг для группы', groupName)
throw e
}
} else {
console.error(page.status, contentType)
console.error(content.length > 500 ? content.slice(0, 500 - 3) + '...' : content)
reportParserError(new Date().toISOString(), 'Не удалось получить страницу для группы', groupName)
throw new Error('Error while fetching lk.ks.psuti.ru')
}
}