Skip to content

fix: update types #341

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

Merged
merged 4 commits into from
Sep 6, 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
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"elysia": "1.1.6",
"elysia-compression": "^0.0.7",
"elysia-helmet": "^2.0.0",
"ky": "^1.7.2",
"node-rsa": "^1.1.1",
"pg": "^8.12.0",
"pg-hstore": "^2.3.4",
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/routes/ads/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { getCookieFromToken } from '@helpers'
import { HeadersWithCookie } from '@utils'

import { adsGetFromDB, saveAds } from 'src/models/Ads/actions'
import { fetcher } from 'src/utils/fetcher'
import type { WithToken } from '../../types'

type Params = WithToken<{
Expand All @@ -18,15 +19,16 @@ export const getAds = async ({
const authData = await getCookieFromToken(token)
const path = `${SERVER_URL}/services/people/organization/news/last/10`
console.log(path)
const response = await fetch(path, {

const response = await fetcher.get(path, {
headers: HeadersWithCookie(authData.cookie)
})

if (!response.ok) {
return adsGetFromDB(spoId)
}

const result = await response.json()
const result = await response.json<NotificationsResponse[]>()

// Попутно сохраняем
saveAds(result, authData)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import type { AttestationResponse } from '@diary-spo/shared'
import { SERVER_URL } from '@config'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import ky from 'ky'

export const getAttestationFromDiary = async (
authData: ICacheData
): Promise<AttestationResponse> => {
const path = `${SERVER_URL}/services/reports/curator/group-attestation-for-student/${authData.idFromDiary}`

return fetch(path, {
headers: HeadersWithCookie(authData.cookie)
})
return ky
.get(path, {
headers: HeadersWithCookie(authData.cookie)
})
.json()
}
30 changes: 21 additions & 9 deletions apps/api/src/routes/auth/login/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { API_ERRORS, NotFoundError, UnknownError } from '@api'
import { SERVER_URL } from '@config'
import { b64 } from '@diary-spo/crypto'
import type { ResponseLogin, UserData } from '@diary-spo/shared'
import { fetcher } from '@utils'

import { fetcher } from 'src/utils/fetcher'
import { offlineAuth } from './service'
import { handleResponse } from './service/helpers'
import { saveUserData } from './service/save'
Expand All @@ -23,11 +24,15 @@ const postAuth = async ({
password = await b64(password)
}

const res = await fetcher<UserData>({
url: `${SERVER_URL}/services/security/login`,
method: 'POST',
body: JSON.stringify({ login, password, isRemember: true })
})
const rawResponse = await fetcher.post(
`${SERVER_URL}/services/security/login`,
{
json: { login, password, isRemember: true }
}
)

const res = await rawResponse.json<UserData>()

const parsedRes = handleResponse(res)

switch (parsedRes) {
Expand All @@ -51,11 +56,18 @@ const postAuth = async ({
* Поэтому проверяем хотя бы наличие одного обязательного поля
**/

if (!parsedRes.data.tenants) {
throw new UnknownError('Unreachable auth error')
const setCookieHeader = rawResponse.headers.get('Set-Cookie')

if (!parsedRes.tenants || !setCookieHeader) {
throw new UnknownError(`Unreachable auth error${parsedRes}`)
}

const userData = await saveUserData(parsedRes, login, password)
const userData = await saveUserData(
parsedRes,
login,
password,
setCookieHeader
)

if (!userData) {
throw new UnknownError('Unreachable auth error')
Expand Down
32 changes: 16 additions & 16 deletions apps/api/src/routes/auth/login/service/save/saveUserData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { API_CODES, ApiError } from '@api'
import { SERVER_URL } from '@config'
import type { PersonResponse, UserData } from '@diary-spo/shared'
import { generateToken } from '@helpers'
import { type ApiResponse, cookieExtractor, error, fetcher } from '@utils'
import { cookieExtractor, error } from '@utils'
import { fetcher } from 'src/utils/fetcher'
import {
getFormattedDiaryUserData,
saveOrGetDiaryUser,
Expand All @@ -11,30 +12,29 @@ import {
import { saveOrGetSPO } from '../../../../../models/SPO'

export const saveUserData = async (
parsedRes: ApiResponse<UserData>,
parsedRes: UserData,
login: string,
password: string
password: string,
setCookieHeader: string
) => {
const tenant = parsedRes.data.tenants[parsedRes.data.tenantName]
const tenant = parsedRes.tenants[parsedRes.tenantName]
const student = tenant.studentRole.students[0]
const SPO = tenant.settings.organization

const setCookieHeader = parsedRes.headers.get('Set-Cookie')
const cookie = cookieExtractor(setCookieHeader ?? '')
try {
const detailedInfo = await fetcher<PersonResponse>({
url: `${SERVER_URL}/services/security/account-settings`,
cookie
})
const rawResponse = await fetcher.get(
`${SERVER_URL}/services/security/account-settings`,
{
headers: {
Cookie: cookie
}
}
)

if (typeof detailedInfo === 'number') {
throw new ApiError(
'Error get detailed info!',
API_CODES.INTERNAL_SERVER_ERROR
)
}
const detailedInfo = await rawResponse.json<PersonResponse>()

const person = detailedInfo.data.person
const person = detailedInfo.persons[0]

const spoAddress =
SPO.actualAddress.length > 5
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/routes/finalMarks/service/get/getFinalMarks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { SERVER_URL } from '@config'
import type { AcademicRecord } from '@diary-spo/shared'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import { fetcher } from 'src/utils/fetcher'

export const getFinalMarksFromDiary = async (authData: ICacheData) => {
const path = `${SERVER_URL}/services/students/${authData.idFromDiary}/attestation`

const response = fetch(path, {
const response = fetcher.get(path, {
headers: HeadersWithCookie(authData.cookie)
})

Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/routes/lessons/service/get/getLessons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Day } from '@diary-spo/shared'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import { detectTerm } from 'src/models/Term/actions/other/detectTerm'
import { fetcher } from 'src/utils/fetcher'
import { ScheduleGetFromDB, daySave } from '../../../../models/Schedule'
import { getFormattedResponse } from '../helpers'

Expand All @@ -15,7 +16,7 @@ export const getLessonsService = async (
): Promise<Day[]> => {
const path = `${SERVER_URL}/services/students/${authData.idFromDiary}/lessons/${startDate}/${endDate}`

const response = await fetch(path, {
const response = await fetcher.get(path, {
headers: HeadersWithCookie(authData.cookie)
})

Expand Down
9 changes: 6 additions & 3 deletions apps/api/src/routes/organization/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Optional } from 'sequelize'
import { API_CODES, API_ERRORS, ApiError } from '@api'
import { SERVER_URL } from '@config'
import { HeadersWithCookie } from '@utils'
import { fetcher } from 'src/utils/fetcher'
import { DiaryUserModel } from '../../models/DiaryUser'
import { GroupModel } from '../../models/Group'
import { SPOModel, type SPOModelType } from '../../models/SPO'
Expand All @@ -18,9 +19,11 @@ const getOrganization = async ({
}: Data): Promise<Optional<SPOModelType, 'id'>> => {
const path = `${SERVER_URL}/services/people/organization`

const response = await fetch(path, {
headers: HeadersWithCookie(cookie)
}).then((res) => res.json())
const response = await fetcher
.get(path, {
headers: HeadersWithCookie(cookie)
})
.json<any>()

if (response) {
/* Хотелось бы красиво по убыванию...
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { SERVER_URL } from '@config'
import type { ICacheData } from '@helpers'
import { HeadersWithCookie } from '@utils'
import { fetcher } from 'src/utils/fetcher'

export const getPerformanceCurrent = async (authData: ICacheData) => {
const path = `${SERVER_URL}/services/reports/current/performance/${authData.idFromDiary}`
console.log(path)

return fetch(path, {
return fetcher.get(path, {
headers: HeadersWithCookie(authData.cookie)
})
}
49 changes: 4 additions & 45 deletions apps/api/src/utils/fetcher.ts
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,46 +1,5 @@
export type HTTPMethods = 'GET' | 'POST'
import ky from 'ky'

export interface ApiResponse<T> {
data: T
headers: Headers
status: number
}

interface Params {
url: string
method?: HTTPMethods
body?: any
cookie?: string
}

export const fetcher = async <T>({
url,
method = 'GET',
body,
cookie
}: Params): Promise<ApiResponse<T> | number> => {
try {
const response = await fetch(url, {
method,
body,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
Cookie: cookie ?? ''
}
})
//console.log(path)
console.log(url)

if (!response.ok) {
return response.status
}

return {
data: (await response.json()) as T,
headers: response.headers,
status: response.status
}
} catch (error) {
return 500
}
}
export const fetcher = ky.extend({
timeout: 10000 // 10 seconds
})
1 change: 0 additions & 1 deletion apps/api/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ export * from './headers'
export * from './formatted'
export * from './error'
export * from './cookieExtractor'
export * from './fetcher'
export * from './errorLogger'
11 changes: 5 additions & 6 deletions apps/api/src/worker/cookieUpdater/submodules/updateUserCookie.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SERVER_URL } from '@config'
import type { UserData } from '@diary-spo/shared'
import { cookieExtractor, fetcher, formatDate } from '@utils'
import { cookieExtractor, formatDate } from '@utils'
import ky from 'ky'
import type { IDiaryUserModel } from '../../../models/DiaryUser'
import { logger } from '../../utils/logger'

Expand All @@ -13,9 +14,7 @@ export const updateUserCookie = async (
console.log('Обновляю cookie пользователя', userInfo)

// 1. Авторизируемся
const res = await fetcher<UserData>({
url: `${SERVER_URL}/services/security/login`,
method: 'POST',
const rawResponse = await ky.post(`${SERVER_URL}/services/security/login`, {
body: JSON.stringify({
login: user.login,
password: user.password,
Expand All @@ -24,13 +23,13 @@ export const updateUserCookie = async (
})

// Если дневник вернул что-то другое...
if (typeof res === 'number') {
if (!rawResponse.ok) {
log('WORKER: Что-то не так... Дневник ответил чем-то другим ?')
return
}

// 2. Подготавливаем куку
const setCookieHeader = res.headers.get('Set-Cookie')
const setCookieHeader = rawResponse.headers.get('Set-Cookie')
const cookie = cookieExtractor(setCookieHeader ?? '')

// 3. Обновляем куку и дату обновления
Expand Down
4 changes: 2 additions & 2 deletions apps/shared/src/api/self/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { Person } from '../../base.ts'

export interface PersonResponse {
person: Person & {
persons: Array<Person & {
login: string
phone: string
birthday: string
isTrusted: boolean
isEsiaBound: boolean
}
}>
}

/**
Expand Down
Binary file modified bun.lockb
Binary file not shown.
Loading