Skip to content

Commit

Permalink
deleted BASE_URL from endpoint definitions. (#604)
Browse files Browse the repository at this point in the history
* deleted BASE_URL from endpoint definitions.
  • Loading branch information
b4rtaz authored Aug 24, 2022
1 parent 29657d7 commit 263779d
Show file tree
Hide file tree
Showing 59 changed files with 118 additions and 153 deletions.
10 changes: 9 additions & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,13 @@
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": ["test-integration", "test-node", "demo-nextjs", "demo-parse-server", "demo-subabase-auth"]
"ignore": [
"test-integration",
"demo-cli",
"demo-nextjs",
"demo-parse-server",
"demo-subabase-auth",
"demo-firebase-auth-functions",
"demo-firebase-proxy-functions"
]
}
7 changes: 6 additions & 1 deletion demos/parse-server/src/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ const makeMoralisErrorMessage = (error: MoralisError) => {
return message;
};

export function errorHandler(error: Error | MoralisError | AxiosError, req: Request, res: Response, _next: NextFunction) {
export function errorHandler(
error: Error | MoralisError | AxiosError,
req: Request,
res: Response,
_next: NextFunction,
) {
// eslint-disable-next-line no-console
console.error('ErrorHandler', error);

Expand Down
4 changes: 2 additions & 2 deletions packages/apiUtils/src/resolvers/EndpointParamsReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class EndpointParamsReader<ApiParams, Params, ApiResult, AdaptedResult, J
return !!this.endpoint.urlParams && this.endpoint.urlParams.includes(param as keyof Params);
}

public getSearchParams(params: ApiParams) {
public getSearchParams(params: ApiParams): Record<string, unknown> {
return Object.keys(params).reduce((result, key) => {
const paramKey = key as keyof ApiParams;

Expand All @@ -26,7 +26,7 @@ export class EndpointParamsReader<ApiParams, Params, ApiResult, AdaptedResult, J
}

return { ...result, [key]: params[paramKey] };
}, {});
}, {} as Record<string, unknown>);
}

public getBodyParams(params: ApiParams) {
Expand Down
3 changes: 2 additions & 1 deletion packages/apiUtils/src/resolvers/EndpointResolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@ describe('ApiResolver', () => {
beforeEach(() => {
resolver = EndpointResolver.create(
core,
API_ROOT,
createEndpointFactory(() =>
createEndpoint({
name: 'endpointWeights',
getUrl: () => `${API_ROOT}/info/endpointWeights`,
getUrl: () => '/info/endpointWeights',
apiToResult: (data: EndpointWeight) => ({
endpoint: data.endpoint,
weight: parseInt(data.weight),
Expand Down
39 changes: 17 additions & 22 deletions packages/apiUtils/src/resolvers/EndpointResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,75 +8,70 @@ import { getCommonHeaders } from './getCommonHeaders';
export class EndpointResolver<ApiParams, Params, ApiResult, AdaptedResult, JSONResult> {
public static create<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>(
core: MoralisCore,
baseUrl: string,
endpointFactory: EndpointFactory<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
) {
const requestController = RequestController.create(core);
const endpoint = endpointFactory(core);
const paramsReader = new EndpointParamsReader(endpoint);
return new EndpointResolver(endpoint, core.config, requestController, paramsReader);
return new EndpointResolver(endpoint, baseUrl, core.config, requestController, paramsReader);
}

public constructor(
public readonly endpoint: Endpoint<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
private readonly baseUrl: string,
private readonly config: Config,
private readonly requestController: RequestController,
private readonly paramsReader: EndpointParamsReader<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
) {}

// TODO: error handler to ApiError
private get = async (params: Params) => {
const url = this.endpoint.getUrl(params);
const url = this.createUrl(params);

const apiParams = this.endpoint.parseParams(params);

const searchParams = this.paramsReader.getSearchParams(apiParams);

// @ts-ignore TODO: fix the ApiParams type, as it should extend Searchparams
const result = await this.requestController.get<ApiResult, ApiParams>(url, searchParams, {
const result = await this.requestController.get<ApiResult>(url, searchParams, {
headers: this.createHeaders(),
});

return new ApiResultAdapter(result, this.endpoint.apiToResult, this.endpoint.resultToJson, params);
};

private post = async (params: Params) => {
const url = this.endpoint.getUrl(params);
const url = this.createUrl(params);
const apiParams = this.endpoint.parseParams(params);

const searchParams = this.paramsReader.getSearchParams(apiParams);
const bodyParams = this.paramsReader.getBodyParams(apiParams);

const result = await this.requestController.post<ApiResult, Record<string, string>, Record<string, string>>(
url,
searchParams,
bodyParams,
{
headers: this.createHeaders(),
},
);
const result = await this.requestController.post<ApiResult, Record<string, string>>(url, searchParams, bodyParams, {
headers: this.createHeaders(),
});

return new ApiResultAdapter(result, this.endpoint.apiToResult, this.endpoint.resultToJson, params);
};

private put = async (params: Params) => {
const url = this.endpoint.getUrl(params);
const url = this.createUrl(params);
const apiParams = this.endpoint.parseParams(params);

const searchParams = this.paramsReader.getSearchParams(apiParams);
const bodyParams = this.paramsReader.getBodyParams(apiParams);

const result = await this.requestController.put<ApiResult, Record<string, string>, Record<string, string>>(
url,
searchParams,
bodyParams,
{
headers: this.createHeaders(),
},
);
const result = await this.requestController.put<ApiResult, Record<string, string>>(url, searchParams, bodyParams, {
headers: this.createHeaders(),
});

return new ApiResultAdapter(result, this.endpoint.apiToResult, this.endpoint.resultToJson, params);
};

private createUrl(params: Params): string {
return this.baseUrl + this.endpoint.getUrl(params);
}

private createHeaders(): { [key: string]: string } {
const apiKey = this.config.get(ApiConfig.apiKey);

Expand Down
15 changes: 4 additions & 11 deletions packages/apiUtils/src/resolvers/Endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,20 @@ export class Endpoints {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly endpoints: Endpoint<unknown, any, any, any, unknown>[] = [];

public constructor(
private readonly core: MoralisCore,
// TODO: the `baseUrl` argument should be removed.
private readonly baseUrl: string,
) {}
public constructor(private readonly core: MoralisCore, private readonly baseUrl: string) {}

public createFetcher<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>(
factory: EndpointFactory<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
) {
const resolver = EndpointResolver.create(this.core, factory);
const resolver = EndpointResolver.create(this.core, this.baseUrl, factory);
this.endpoints.push(resolver.endpoint);
return resolver.fetch;
}

public createPaginatedFetcher<ApiParams, Params extends PaginatedParams, ApiResult, AdaptedResult, JSONResult>(
factory: PaginatedEndpointFactory<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
) {
const resolver = PaginatedEndpointResolver.create(this.core, factory);
const resolver = PaginatedEndpointResolver.create(this.core, this.baseUrl, factory);
this.endpoints.push(resolver.endpoint);
return resolver.fetch;
}
Expand All @@ -50,10 +46,7 @@ export class Endpoints {
params[paramName] = `{${paramName}}`;
return params;
}, {});
const urlPattern = endpoint
.getUrl(urlParams)
// TODO: getUrl() method should NOT return url with baseUrl prefix!
.replace(this.baseUrl, '');
const urlPattern = endpoint.getUrl(urlParams);

return {
// DO NOT return baseUrl here!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,11 @@ describe('PaginatedEndpointResolver', () => {
beforeEach(() => {
resolver = PaginatedEndpointResolver.create(
core,
API_ROOT,
createPaginatedEndpointFactory(() =>
createPaginatedEndpoint({
name: 'getContractEvents',
getUrl: (params: Params) => `${API_ROOT}/${params.address}/events`,
getUrl: (params: Params) => `/${params.address}/events`,
// TODO: remove PaginatedResponse when api squad make swagger update
apiToResult: (data: PaginatedResult<ApiResult>) =>
data.result.map((event) => ({
Expand Down
30 changes: 18 additions & 12 deletions packages/apiUtils/src/resolvers/PaginatedEndpointResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,18 @@ export class PaginatedEndpointResolver<
> {
public static create<ApiParams, Params extends PaginatedParams, ApiResult, AdaptedResult, JSONResult>(
core: MoralisCore,
baseUrl: string,
endpointFactory: PaginatedEndpointFactory<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
) {
const requestController = RequestController.create(core);
const endpoint = endpointFactory(core);
const paramsReader = new EndpointParamsReader(endpoint);
return new PaginatedEndpointResolver(endpoint, core.config, requestController, paramsReader);
return new PaginatedEndpointResolver(endpoint, baseUrl, core.config, requestController, paramsReader);
}

public constructor(
public readonly endpoint: PaginatedEndpoint<ApiParams, Params, ApiResult, AdaptedResult, JSONResult>,
private readonly baseUrl: string,
private readonly config: Config,
private readonly requestController: RequestController,
private readonly paramsReader: EndpointParamsReader<
Expand All @@ -38,14 +40,13 @@ export class PaginatedEndpointResolver<

// TODO: error handler to ApiError
private get = async (params: Params) => {
const url = this.endpoint.getUrl(params);
const url = this.createUrl(params);

const apiParams = this.endpoint.parseParams(params);

const searchParams = this.paramsReader.getSearchParams(apiParams);

// @ts-ignore TODO: fix the ApiParams type, as it should extend Searchparams
const result = await this.requestController.get<PaginatedResult<ApiResult>, ApiParams>(url, searchParams, {
const result = await this.requestController.get<PaginatedResult<ApiResult>>(url, searchParams, {
headers: this.createHeaders(),
});

Expand All @@ -59,19 +60,20 @@ export class PaginatedEndpointResolver<
};

private post = async (params: Params) => {
const url = this.endpoint.getUrl(params);
const url = this.createUrl(params);
const apiParams = this.endpoint.parseParams(params);

const searchParams = this.paramsReader.getSearchParams(apiParams);
const bodyParams = this.paramsReader.getBodyParams(apiParams);

const result = await this.requestController.post<
PaginatedResult<ApiResult>,
Record<string, string>,
Record<string, string>
>(url, searchParams, bodyParams, {
headers: this.createHeaders(),
});
const result = await this.requestController.post<PaginatedResult<ApiResult>, Record<string, string>>(
url,
searchParams,
bodyParams,
{
headers: this.createHeaders(),
},
);

return new ApiPaginatedResultAdapter(
result,
Expand All @@ -87,6 +89,10 @@ export class PaginatedEndpointResolver<
return checkObjEqual(params, nextParams) ? undefined : () => this.fetch(nextParams);
};

private createUrl(params: Params): string {
return this.baseUrl + this.endpoint.getUrl(params);
}

private createHeaders(): { [key: string]: string } {
const apiKey = this.config.get(ApiConfig.apiKey);
if (!apiKey) {
Expand Down
3 changes: 2 additions & 1 deletion packages/auth/src/methods/requestMessage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { EndpointResolver } from '@moralisweb3/api-utils';
import MoralisCore, { AuthErrorCode, MoralisAuthError } from '@moralisweb3/core';
import { EvmAddress, EvmAddressish, EvmChain, EvmChainish } from '@moralisweb3/evm-utils';
import { BASE_URL } from '../MoralisAuth';
import { initializeChallenge } from '../resolvers/evmRequestChallenge';

export enum AuthNetwork {
Expand Down Expand Up @@ -31,7 +32,7 @@ const makeEvmRequestMessage = (
core: MoralisCore,
{ chain, address, network, ...options }: RequestMessageEvmOptions,
) => {
return EndpointResolver.create(core, initializeChallenge).fetch({
return EndpointResolver.create(core, BASE_URL, initializeChallenge).fetch({
chainId: EvmChain.create(chain).decimal,
address: EvmAddress.create(address).checksum,
...options,
Expand Down
3 changes: 2 additions & 1 deletion packages/auth/src/methods/verify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { EndpointResolver } from '@moralisweb3/api-utils';
import MoralisCore, { assertUnreachable } from '@moralisweb3/core';
import { BASE_URL } from '../MoralisAuth';
import { completeChallenge } from '../resolvers/evmVerifyChallenge';

export interface VerifyEvmOptions {
Expand All @@ -12,7 +13,7 @@ export type VerifyOptions = VerifyEvmOptions;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const makeEvmVerify = (core: MoralisCore, { network, ...options }: VerifyEvmOptions) => {
return EndpointResolver.create(core, completeChallenge).fetch({
return EndpointResolver.create(core, BASE_URL, completeChallenge).fetch({
message: options.message,
signature: options.signature,
});
Expand Down
3 changes: 1 addition & 2 deletions packages/auth/src/resolvers/evmRequestChallenge.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createEndpoint, createEndpointFactory } from '@moralisweb3/api-utils';
import { toCamelCase } from '@moralisweb3/core';
import { operations } from '../generated/types';
import { BASE_URL } from '../MoralisAuth';

const name = 'requestChallengeEvm';

Expand Down Expand Up @@ -35,7 +34,7 @@ const apiToResult = (apiData: ApiResult) => {
export const initializeChallenge = createEndpointFactory(() =>
createEndpoint({
name,
getUrl: () => `${BASE_URL}/challenge/request/evm`,
getUrl: () => `/challenge/request/evm`,
apiToResult,
resultToJson: (data) => ({
...data,
Expand Down
3 changes: 1 addition & 2 deletions packages/auth/src/resolvers/evmVerifyChallenge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { maybe, toCamelCase } from '@moralisweb3/core';
import { EvmAddress, EvmChain } from '@moralisweb3/evm-utils';
import { createEndpoint, createEndpointFactory } from '@moralisweb3/api-utils';
import { operations } from '../generated/types';
import { BASE_URL } from '../MoralisAuth';

const name = 'verifyChallengeEvm';

Expand All @@ -18,7 +17,7 @@ type ApiResult = operations[Name]['responses']['201']['content']['application/js
export const completeChallenge = createEndpointFactory(() =>
createEndpoint({
name: 'Verify Challenge (EVM)',
getUrl: () => `${BASE_URL}/challenge/verify/evm`,
getUrl: () => `/challenge/verify/evm`,
apiToResult: ({ chainId, ...data }: ApiResult) => ({
...data,
// TODO: revisit EVM logic once we know how authentication in other networks work
Expand Down
12 changes: 6 additions & 6 deletions packages/core/src/controllers/RequestController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ export class RequestController {
});
}

public post<Response, SearchParams extends Record<string, string>, Body extends Record<string, unknown>>(
public post<Response, Body extends Record<string, unknown>>(
url: string,
searchParams?: SearchParams,
searchParams?: Record<string, unknown>,
body?: Body,
options?: RequestOptions,
abortSignal?: AbortController['signal'],
Expand All @@ -112,9 +112,9 @@ export class RequestController {
});
}

public put<Response, SearchParams extends Record<string, string>, Body extends Record<string, unknown>>(
public put<Response, Body extends Record<string, unknown>>(
url: string,
searchParams?: SearchParams,
searchParams?: Record<string, unknown>,
body?: Body,
options?: RequestOptions,
abortSignal?: AbortController['signal'],
Expand All @@ -129,9 +129,9 @@ export class RequestController {
});
}

public async get<Response, SearchParams extends Record<string, string>>(
public async get<Response>(
url: string,
searchParams?: SearchParams,
searchParams?: Record<string, unknown>,
options?: RequestOptions,
abortSignal?: AbortController['signal'],
): Promise<Response> {
Expand Down
2 changes: 1 addition & 1 deletion packages/evmApi/src/EvmApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import { uploadFolder } from './resolvers/storage';
import { EvmApiConfigSetup } from './config/EvmApiConfigSetup';
import { Endpoints } from '@moralisweb3/api-utils';

export const BASE_URL = 'https://deep-index.moralis.io/api/v2';
const BASE_URL = 'https://deep-index.moralis.io/api/v2';

export class MoralisEvmApi extends ApiModule {
public static readonly moduleName = 'evmApi';
Expand Down
Loading

0 comments on commit 263779d

Please sign in to comment.