Skip to content
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
116 changes: 115 additions & 1 deletion app/api/server/api.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,118 @@
import { APIClass } from '.';
import { Endpoints } from '../../../definition/rest';
import { Awaited } from '../../../definition/utils';
import { IUser } from '../../../definition/IUser';


export type ChangeTypeOfKeys<
T extends object,
Keys extends keyof T,
NewType
> = {
[key in keyof T]: key extends Keys ? NewType : T[key]
}

type This = {
getPaginationItems(): ({
offset: number;
count: number;
});
parseJsonQuery(): ({
sort: Record<string, unknown>;
fields: Record<string, unknown>;
query: Record<string, unknown>;
});
readonly urlParams: Record<string, unknown>;
getUserFromParams(): IUser;
}

type ThisLoggedIn = {
readonly user: IUser;
readonly userId: string;
}

type ThisLoggedOut = {
readonly user: null;
readonly userId: null;
}

type EndpointWithExtraOptions<FN extends (this: any, ...args: any) => any, A> = WrappedFunction<FN> | ({ action: WrappedFunction<FN> } & (A extends true ? { twoFactorRequired: boolean } : {}));

export type Methods<T, A = false> = {
[K in keyof T as `${Lowercase<string & K>}`]: T[K] extends (...args: any) => any ? EndpointWithExtraOptions<(this: This & (A extends true ? ThisLoggedIn : ThisLoggedOut) & Params<K, Parameters<T[K]>[0]>) => ReturnType<T[K]>, A> : never;
};

type Params<K, P> = K extends 'GET' ? { readonly queryParams: Partial<P> } : K extends 'POST' ? { readonly bodyParams: Partial<P> } : never;

type SuccessResult<T = undefined> = {
statusCode: 200;
success: true;
} & T extends (undefined) ? {} : { body: T }

type UnauthorizedResult = {
statusCode: 403;
body: {
success: false;
error: string;
};
}

type FailureResult<T = undefined, ET = undefined, ST = undefined, E = undefined> = {
statusCode: 400;
} & FailureBody<T, ET, ST, { success: false }>;

type FailureBody<T, ET, ST, E> = Exclude<T, string> extends object ? { body: T & E } : {
body: E & { error: string } & E extends Error ? { details: string } : {} & ST extends undefined ? {} : { stack: string } & ET extends undefined ? {} : { errorType: string };
}

type Errors = FailureResult | FailureResult<object> | FailureResult<string, string, string, { error: string }> | UnauthorizedResult;

type WrappedFunction<T extends (this: any, ...args: any) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnTypes<T>;

type ReturnTypes<T extends (this: any, ...args: any) => any> = PromisedOrNot<SuccessResult<ReturnType<T>> | PromisedOrNot<Errors>>;

type PromisedOrNot<T> = Promise<T> | T;

type Options = {
permissionsRequired?: string[];
twoFactorOptions?: unknown;
twoFactorRequired?: boolean;
authRequired?: boolean;
}

export type RestEndpoints<P extends keyof Endpoints, A = false> = Methods<Endpoints[P], A>;

type ToLowerCaseKeys<T> = {
[K in keyof T as `${Lowercase<string & K>}`]: T[K];
};
type ToResultType<T> = {
[K in keyof T]: T[K] extends (...args: any) => any ? Awaited<ReturnTypes<T[K]>> : never;
}
export type ResultTypeEndpoints<P extends keyof Endpoints, A = false> = ToResultType<ToLowerCaseKeys<Endpoints[P]>>;

declare class APIClass {
addRoute<P extends keyof Endpoints>(route: P, endpoints: RestEndpoints<P>): void;

addRoute<P extends keyof Endpoints, O extends Options>(route: P, options: O, endpoints: RestEndpoints<P, O['authRequired'] extends true ? true: false>): void;

unauthorized(msg?: string): UnauthorizedResult;

failure<ET = string | undefined, ST = string | undefined, E = Error | undefined>(result: string, errorType?: ET, stack?: ST, error?: E): FailureResult<string, ET, ST, E>;

failure(result: object): FailureResult<object>;

failure(): FailureResult;

success(): SuccessResult<void>;

success<T>(result: T): SuccessResult<T>;

defaultFieldsToExclude: {
joinCode: 0;
members: 0;
importIds: 0;
e2e: 0;
}
}

export declare const API: {
v1: APIClass;
Expand Down
2 changes: 1 addition & 1 deletion app/api/server/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ export class APIClass extends Restivus {
api.processTwoFactor({ userId: this.userId, request: this.request, invocation, options: _options.twoFactorOptions, connection });
}

result = DDP._CurrentInvocation.withValue(invocation, () => originalAction.apply(this)) || API.v1.success();
result = DDP._CurrentInvocation.withValue(invocation, () => Promise.await(originalAction.apply(this))) || API.v1.success();

log.http({
status: result.statusCode,
Expand Down
2 changes: 1 addition & 1 deletion app/api/server/helpers/getPaginationItems.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ API.helperMethods.set('getPaginationItems', function _getPaginationItems() {
const offset = this.queryParams.offset ? parseInt(this.queryParams.offset) : 0;
let count = defaultCount;

// Ensure count is an appropiate amount
// Ensure count is an appropriate amount
if (typeof this.queryParams.count !== 'undefined') {
count = parseInt(this.queryParams.count);
} else {
Expand Down
23 changes: 14 additions & 9 deletions app/api/server/v1/banners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import { BannerPlatform } from '../../../../definition/IBanner';
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('banners.getNew', { authRequired: true }, { // deprecated
get() {
async get() {
check(this.queryParams, Match.ObjectIncluding({
platform: String,
bid: Match.Maybe(String),
Expand All @@ -67,7 +67,7 @@ API.v1.addRoute('banners.getNew', { authRequired: true }, { // deprecated
throw new Meteor.Error('error-unknown-platform', 'Platform is unknown.');
}

const banners = Promise.await(Banner.getBannersForUser(this.userId, platform, bannerId));
const banners = await Banner.getBannersForUser(this.userId, platform, bannerId);

return API.v1.success({ banners });
},
Expand Down Expand Up @@ -119,13 +119,18 @@ API.v1.addRoute('banners.getNew', { authRequired: true }, { // deprecated
* schema:
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('banners/:id', { authRequired: true }, {
get() {
API.v1.addRoute('banners/:id', { authRequired: true }, { // TODO: move to users/:id/banners
async get() {
check(this.urlParams, Match.ObjectIncluding({
id: String,
}));

check(this.queryParams, Match.ObjectIncluding({
platform: String,
}));

const { platform } = this.queryParams;

if (!platform) {
throw new Meteor.Error('error-missing-param', 'The required "platform" param is missing.');
}
Expand All @@ -135,7 +140,7 @@ API.v1.addRoute('banners/:id', { authRequired: true }, {
throw new Meteor.Error('error-missing-param', 'The required "id" param is missing.');
}

const banners = Promise.await(Banner.getBannersForUser(this.userId, platform, id));
const banners = await Banner.getBannersForUser(this.userId, platform, id);

return API.v1.success({ banners });
},
Expand Down Expand Up @@ -179,7 +184,7 @@ API.v1.addRoute('banners/:id', { authRequired: true }, {
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('banners', { authRequired: true }, {
get() {
async get() {
check(this.queryParams, Match.ObjectIncluding({
platform: String,
}));
Expand All @@ -193,7 +198,7 @@ API.v1.addRoute('banners', { authRequired: true }, {
throw new Meteor.Error('error-unknown-platform', 'Platform is unknown.');
}

const banners = Promise.await(Banner.getBannersForUser(this.userId, platform));
const banners = await Banner.getBannersForUser(this.userId, platform);

return API.v1.success({ banners });
},
Expand Down Expand Up @@ -233,7 +238,7 @@ API.v1.addRoute('banners', { authRequired: true }, {
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('banners.dismiss', { authRequired: true }, {
post() {
async post() {
check(this.bodyParams, Match.ObjectIncluding({
bannerId: String,
}));
Expand All @@ -244,7 +249,7 @@ API.v1.addRoute('banners.dismiss', { authRequired: true }, {
throw new Meteor.Error('error-missing-param', 'The required "bannerId" param is missing.');
}

Promise.await(Banner.dismiss(this.userId, bannerId));
await Banner.dismiss(this.userId, bannerId);
return API.v1.success();
},
});
6 changes: 3 additions & 3 deletions app/api/server/v1/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -697,15 +697,15 @@ API.v1.addRoute('chat.getSnippetedMessages', { authRequired: true }, {
});

API.v1.addRoute('chat.getDiscussions', { authRequired: true }, {
get() {
async get() {
const { roomId, text } = this.queryParams;
const { sort } = this.parseJsonQuery();
const { offset, count } = this.getPaginationItems();

if (!roomId) {
throw new Meteor.Error('error-invalid-params', 'The required "roomId" query param is missing.');
}
const messages = Promise.await(findDiscussionsFromRoom({
const messages = await findDiscussionsFromRoom({
uid: this.userId,
roomId,
text,
Expand All @@ -714,7 +714,7 @@ API.v1.addRoute('chat.getDiscussions', { authRequired: true }, {
count,
sort,
},
}));
});
return API.v1.success(messages);
},
});
8 changes: 4 additions & 4 deletions app/api/server/v1/dns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { resolveSRV, resolveTXT } from '../../../federation/server/functions/res
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('dns.resolve.srv', { authRequired: true }, {
get() {
async get() {
check(this.queryParams, Match.ObjectIncluding({
url: String,
}));
Expand All @@ -58,7 +58,7 @@ API.v1.addRoute('dns.resolve.srv', { authRequired: true }, {
throw new Meteor.Error('error-missing-param', 'The required "url" param is missing.');
}

const resolved = Promise.await(resolveSRV(url));
const resolved = await resolveSRV(url);

return API.v1.success({ resolved });
},
Expand Down Expand Up @@ -99,7 +99,7 @@ API.v1.addRoute('dns.resolve.srv', { authRequired: true }, {
* $ref: '#/components/schemas/ApiFailureV1'
*/
API.v1.addRoute('dns.resolve.txt', { authRequired: true }, {
post() {
async post() {
check(this.queryParams, Match.ObjectIncluding({
url: String,
}));
Expand All @@ -109,7 +109,7 @@ API.v1.addRoute('dns.resolve.txt', { authRequired: true }, {
throw new Meteor.Error('error-missing-param', 'The required "url" param is missing.');
}

const resolved = Promise.await(resolveTXT(url));
const resolved = await resolveTXT(url);

return API.v1.success({ resolved });
},
Expand Down
4 changes: 2 additions & 2 deletions app/api/server/v1/instances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import { InstanceStatus } from '../../../models/server/raw';
import { IInstanceStatus } from '../../../../definition/IInstanceStatus';

API.v1.addRoute('instances.get', { authRequired: true }, {
get() {
async get() {
if (!hasPermission(this.userId, 'view-statistics')) {
return API.v1.unauthorized();
}

const instances = Promise.await(InstanceStatus.find().toArray());
const instances = await InstanceStatus.find().toArray();

return API.v1.success({
instances: instances.map((instance: IInstanceStatus) => {
Expand Down
12 changes: 6 additions & 6 deletions app/api/server/v1/ldap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { SystemLogger } from '../../../../server/lib/logger/system';
import { LDAP } from '../../../../server/sdk';

API.v1.addRoute('ldap.testConnection', { authRequired: true }, {
post() {
async post() {
if (!this.userId) {
throw new Error('error-invalid-user');
}
Expand All @@ -21,20 +21,20 @@ API.v1.addRoute('ldap.testConnection', { authRequired: true }, {
}

try {
Promise.await(LDAP.testConnection());
await LDAP.testConnection();
} catch (error) {
SystemLogger.error(error);
throw new Error('Connection_failed');
}

return API.v1.success({
message: 'Connection_success',
message: 'Connection_success' as const,
});
},
});

API.v1.addRoute('ldap.testSearch', { authRequired: true }, {
post() {
async post() {
check(this.bodyParams, Match.ObjectIncluding({
username: String,
}));
Expand All @@ -51,10 +51,10 @@ API.v1.addRoute('ldap.testSearch', { authRequired: true }, {
throw new Error('LDAP_disabled');
}

Promise.await(LDAP.testSearch(this.bodyParams.username));
await LDAP.testSearch(this.bodyParams.username);

return API.v1.success({
message: 'LDAP_User_Found',
message: 'LDAP_User_Found' as const,
});
},
});
Loading