import type { Serialized } from '@rocket.chat/core-typings'; import type { Method, PathPattern, OperationParams, UrlParams, OperationResult } from '@rocket.chat/rest-typings'; import type { EndpointFunction, ServerContextValue } from '@rocket.chat/ui-contexts'; import { ServerContext } from '@rocket.chat/ui-contexts'; import { useMemo } from 'react'; import type { ContextType, ReactNode } from 'react'; type RegisterEndpoint = ( method: TMethod, pathPattern: TPathPattern, endpoint: EndpointFunction, ) => void; type CallEndpoint = (args: { method: TMethod; pathPattern: TPathPattern; keys: UrlParams; params: OperationParams; }) => Promise>>; // this function should be used to create a new instance of `callEndpoint` to be passed to the `ServerProviderMock` // as the second parameter, it returns a function that can be used to register endpoint mocks // the rest should be self-explanatory, just rely on the types. export const makeCallEndpoint = (): [CallEndpoint, RegisterEndpoint] => { const endpoints = new Map<`${Method}/${PathPattern}`, (params: any) => Promise>(); const getEndpoint = ( method: TMethod, pathPattern: TPathPattern, ): EndpointFunction => { const endpoint = endpoints.get(`${method}/${pathPattern}`); if (!endpoint) { throw new Error('Endpoint not implemented'); } return endpoint as EndpointFunction; }; const registerEndpoint: RegisterEndpoint = (method, pathPattern, endpoint) => { endpoints.set(`${method}/${pathPattern}`, endpoint); }; const callEndpoint: CallEndpoint = (args) => { const endpoint = getEndpoint(args.method, args.pathPattern); if (!endpoint) { throw new Error('Endpoint not implemented'); } return endpoint(args.params); }; return [callEndpoint, registerEndpoint]; }; const absoluteUrl = () => ''; // to be implemented const uploadToEndpoint = async () => { throw new Error('not implemented'); }; // to be implemented const getStream = () => () => () => undefined; // to be implemented const getStreamAll = () => () => () => undefined; // to be implemented const callEndpoint = () => { throw new Error('not implemented'); }; // to be implemented const writeStream = () => undefined; // to be implemented const contextValue: ServerContextValue = { connected: true, status: 'connected', retryCount: 0, info: undefined, absoluteUrl, // callMethod, callEndpoint, uploadToEndpoint, getStream, getStreamAll, reconnect: () => undefined, disconnect: () => undefined, writeStream, }; export type ServerProviderMockProps = { children?: ReactNode; callEndpoint?: ContextType['callEndpoint']; }; const ServerProviderMock = ({ children, callEndpoint }: ServerProviderMockProps) => { const value = useMemo(() => ({ ...contextValue, callEndpoint: callEndpoint ?? contextValue.callEndpoint }), [callEndpoint]); return {children}; }; export default ServerProviderMock;