import { NativeModules, Platform } from 'react-native' import type { GraphQLError } from 'graphql' import type { InterceptorsResult, NetworkErrorType } from '../interface' import type { Operation } from '@apollo/client' import { print } from '@apollo/client/utilities' export function request(url: RequestInfo, options: RequestInit) { const newOptions: RequestInit = { method: 'GET', ...(options || {}), } return fetch(url, { ...newOptions, }).then(response => { if (!response.ok) { throw new Error(`错误码:${response.status}`) } return response.json() }) } /* * 判断当前手机是否为鸿蒙系统 */ export async function isHarmony(): Promise { if (Platform.OS === 'ios') { return false } try { const res = await NativeModules.DeviceApi.isHarmony() return res } catch (err) { return false } } export function getRequestTime(params: { requestName: string requestStartTime: number type: 'graphql' | 'restful' }) { const requestEndTime = new Date().getTime() const requestDurationTime = requestEndTime - params?.requestStartTime return { type: params?.type, requestName: params?.requestName, requestStartTime: params?.requestStartTime, requestEndTime, requestDurationTime: `${(requestDurationTime / 1000).toFixed(2)}s`, } } export function formatGraphqlError( error: GraphQLError, ): Partial { const { message, locations, path } = error const err = new Error( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ) return { en: err.name, em: err.message, es: err.stack, createTime: Date.now(), path: error.path, location: error.locations?.map(item => ({ line: item.line, column: item.column, })), extensions: error.extensions, t: 'e', } } export function formatRestfulError( errorCode: number, errorMessage: string, path?: string, ): Partial { const error = new Error( `[Restful error]: Code: ${errorCode}, Message: ${errorMessage}, Path: ${path}`, ) return { en: error?.name, em: error?.message, es: error?.stack, createTime: new Date().getTime(), } } /** * 获取graphql操作的上报信息 * @param operation * @returns */ export function getGqlOperation(operation: Operation) { return { _t: 'GRAPHQL', n: operation.operationName, ct: Date.now(), dur: Date.now() - operation.getContext().time, arg: operation.variables ? JSON.stringify(operation.variables) : null, qs: print(operation.query), t: 'api', } } /** * 获取restful操作的上报信息 * @param operation * @returns */ export function getRestfulOperation(response: InterceptorsResult) { const _request = response.request const _url = _request?._url const _perfKey = _request?._perfKey const totalTime = _request?._performanceLogger._timespans?.[_perfKey]?.totalTime const config = response.config return { _t: 'RESTFUL', n: _url, ct: Date.now(), dur: totalTime, arg: config.method === 'get' ? config.params ? JSON.stringify(config.params) : null : config.method === 'post' ? config.data ? typeof config.data === 'string' ? config.data : JSON.stringify(config.data) : null : null, t: 'api', } }