Skip to content

Commit

Permalink
Removed circular references (jdalrymple#1387)
Browse files Browse the repository at this point in the history
- Updated requester structure
- Removed duplicate pipeline jobs function
  • Loading branch information
jdalrymple authored Dec 18, 2020
1 parent 7807c63 commit 565bd15
Show file tree
Hide file tree
Showing 84 changed files with 340 additions and 697 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Available instantiating options:
| `sudo` | Yes | `false` | [Sudo](https://docs.gitlab.com/ee/api/#sudo) query parameter |
| `version` | Yes | `4` | API Version ID |
| `camelize` | Yes | `false` | Camelizes all response body keys |
| `requester` | Yes\* | @gitbeaker/node & @gitbeaker/cli : Got-based, @gitbeaker/browser: Ky-based. The @gitbeaker/core package **does not** have a default and thus must be set explicitly | Request Library Wrapper | |
| `requesterFn` | Yes\* | @gitbeaker/node & @gitbeaker/cli : Got-based, @gitbeaker/browser: Ky-based. The @gitbeaker/core package **does not** have a default and thus must be set explicitly | Request Library Wrapper | |
| `requestTimeout` | Yes | `300000` | Request Library Timeout in ms |
| `profileToken` | Yes | N/A | [Requests Profiles Token](https://docs.gitlab.com/ee/administration/monitoring/performance/request_profiling.html) |
| `profileMode` | Yes | `execution` | [Requests Profiles Token](https://docs.gitlab.com/ee/administration/monitoring/performance/request_profiling.html) |
Expand Down
27 changes: 15 additions & 12 deletions packages/gitbeaker-browser/src/KyRequester.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import ky from 'ky';
import { Agent } from 'https';
import {
DefaultRequestService,
DefaultServiceOptions,
DefaultRequestReturn,
DefaultRequestOptions,
createInstance,
defaultRequest as baseDefaultRequest,
createRequesterFn,
defaultOptionsHandler as baseOptionsHandler,
wait,
} from '@gitbeaker/requester-utils';

Expand All @@ -19,23 +19,26 @@ function responseHeadersAsObject(response): Record<string, string> {
return headers;
}

export function defaultRequest(
service: DefaultRequestService,
export function defaultOptionsHandler(
serviceOptions: DefaultServiceOptions,
options: DefaultRequestOptions = {},
): DefaultRequestReturn & { agent?: Agent } {
const opts: DefaultRequestReturn & { agent?: Agent } = baseDefaultRequest(service, options);
const opts: DefaultRequestReturn & { agent?: Agent } = baseOptionsHandler(
serviceOptions,
options,
);

if (
service.url.includes('https') &&
service.rejectUnauthorized != null &&
service.rejectUnauthorized === false
serviceOptions.url.includes('https') &&
serviceOptions.rejectUnauthorized != null &&
serviceOptions.rejectUnauthorized === false
) {
opts.agent = new Agent({
rejectUnauthorized: service.rejectUnauthorized,
rejectUnauthorized: serviceOptions.rejectUnauthorized,
});
}

return { ...opts, headers: new Headers(service.headers as Record<string, string>) };
return { ...opts, headers: new Headers(serviceOptions.headers as Record<string, string>) };
}

export function processBody(response) {
Expand Down Expand Up @@ -95,4 +98,4 @@ export async function handler(endpoint: string, options: Record<string, unknown>
return { body, headers, status };
}

export const Requester = createInstance(defaultRequest, handler);
export const requesterFn = createRequesterFn(defaultOptionsHandler, handler);
4 changes: 2 additions & 2 deletions packages/gitbeaker-browser/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as Gitbeaker from '@gitbeaker/core';
import { modifyServices } from '@gitbeaker/requester-utils';
import { Requester } from './KyRequester';
import { requesterFn } from './KyRequester';

const { getAPIMap, ...services } = Gitbeaker;
const APIServices = modifyServices(services, { requester: Requester });
const APIServices = modifyServices(services, { requesterFn });

export const {
// Groups
Expand Down
10 changes: 5 additions & 5 deletions packages/gitbeaker-browser/test/unit/KyRequester.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as ky from 'ky';
import * as fetch from 'node-fetch';
import { Agent } from 'https';
import { processBody, handler, defaultRequest } from '../../src/KyRequester';
import { processBody, handler, defaultOptionsHandler } from '../../src/KyRequester';

// Set globals for testing purposes
if (!global.fetch) {
Expand Down Expand Up @@ -167,7 +167,7 @@ describe('defaultRequest', () => {

it('should stringify body if it isnt of type FormData', async () => {
const testBody = { test: 6 };
const { body, headers } = defaultRequest(service, {
const { body, headers } = defaultOptionsHandler(service, {
body: testBody,
});

Expand All @@ -176,22 +176,22 @@ describe('defaultRequest', () => {
});

it('should assign the agent property if given https url and rejectUnauthorized is false', async () => {
const { agent = {} } = defaultRequest(
const { agent = {} } = defaultOptionsHandler(
{ ...service, url: 'https://test.com', rejectUnauthorized: false },
{ method: 'post' },
);

expect(agent).toBeInstanceOf(Agent);
expect(agent.rejectUnauthorized).toBeFalsy();

const { agent: agent2 } = defaultRequest(
const { agent: agent2 } = defaultOptionsHandler(
{ ...service, url: 'https://test.com', rejectUnauthorized: true },
{ method: 'post' },
);

expect(agent2).toBeUndefined();

const { agent: agent3 } = defaultRequest(
const { agent: agent3 } = defaultOptionsHandler(
{ ...service, url: 'https://test.com' },
{ method: 'post' },
);
Expand Down
2 changes: 1 addition & 1 deletion packages/gitbeaker-core/scripts/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function buildMap() {
for (const [name, service] of Object.entries(Gitbeaker as object)) {
if (name.includes('Bundle') || ['Gitlab', 'getAPIMap'].includes(name)) continue;

const s = new service({ requester: {} });
const s = new service({ requesterFn: () => ({}) });

map[name] = [{ name: 'constructor', args: baseArgs }];

Expand Down
10 changes: 5 additions & 5 deletions packages/gitbeaker-core/src/infrastructure/RequestHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async function getHelper<T = Record<string, unknown>>(
}: PaginatedRequestOptions | OffsetPaginatedRequestOptions = {},
acc: any[] = [],
): Promise<any> {
const response = await service.requester.get(service, endpoint, { query, sudo });
const response = await service.requester.get(endpoint, { query, sudo });
const { headers, status } = response;
let { body } = response;

Expand Down Expand Up @@ -160,7 +160,7 @@ async function post(
): Promise<any> {
const body = isForm ? appendFormFromObject(options) : options;

const r = await service.requester.post(service, endpoint, {
const r = await service.requester.post(endpoint, {
body,
sudo,
});
Expand Down Expand Up @@ -191,7 +191,7 @@ async function put(
endpoint: string,
{ sudo, showExpanded, ...body }: ShowExpanded & BaseRequestOptions = {},
): Promise<any> {
const r = await service.requester.put(service, endpoint, {
const r = await service.requester.put(endpoint, {
body,
sudo,
});
Expand All @@ -216,7 +216,7 @@ async function del(
endpoint: string,
{ sudo, showExpanded, ...query }: ShowExpanded & BaseRequestOptions = {},
): Promise<any> {
const r = await service.requester.delete(service, endpoint, {
const r = await service.requester.delete(endpoint, {
query,
sudo,
});
Expand All @@ -233,7 +233,7 @@ function stream(
throw new Error('Stream method is not implementated in requester!');
}

return service.requester.stream(service, endpoint, {
return service.requester.stream(endpoint, {
query: options,
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/gitbeaker-core/src/infrastructure/Utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as FormData from 'form-data';
import FormData from 'form-data';

/* eslint @typescript-eslint/no-explicit-any: 0 */
interface Constructor {
Expand Down
6 changes: 3 additions & 3 deletions packages/gitbeaker-core/src/services/Jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import {
Sudo,
} from '../infrastructure';
import { CommitSchemaDefault, CommitSchemaCamelized } from './Commits';
import { PipelineSchemaDefault, PipelineSchemaCamelized } from './Pipelines';
import { RunnerSchemaDefault, RunnerSchemaCamelized } from './Runners';
import { UserSchemaDefault, UserSchemaCamelized } from './Users';
import { PipelineBase } from './Pipelines';

export type JobScope =
| 'created'
Expand Down Expand Up @@ -52,7 +52,7 @@ export interface JobSchemaDefault {
duration?: number;
user: UserSchemaDefault;
commit: CommitSchemaDefault;
pipeline: PipelineSchemaDefault;
pipeline: PipelineBase;
web_url: string;
artifacts: ArtifactSchemaDefault[];
runner: RunnerSchemaDefault;
Expand All @@ -74,7 +74,7 @@ export interface JobSchemaCamelized {
duration?: number;
user: UserSchemaCamelized;
commit: CommitSchemaCamelized;
pipeline: PipelineSchemaCamelized;
pipeline: PipelineBase;
webUrl: string;
artifacts: ArtifactSchemaCamelized[];
runner: RunnerSchemaCamelized;
Expand Down
33 changes: 19 additions & 14 deletions packages/gitbeaker-core/src/services/Pipelines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,34 @@ import {
RequestHelper,
Sudo,
} from '../infrastructure';
import { JobScope } from './Jobs';

export interface PipelineSchemaDefault {
export type PipelineStatus =
| 'created'
| 'waiting_for_resource'
| 'preparing'
| 'pending'
| 'running'
| 'failed'
| 'success'
| 'canceled'
| 'skipped'
| 'manual'
| 'scheduled';

export interface PipelineBase {
id: number;
sha: string;
ref: string;
status: string;
status: PipelineStatus;
}

export interface PipelineSchemaDefault extends PipelineBase {
created_at: Date;
updated_at: Date;
web_url: string;
}

export interface PipelineSchemaCamelized {
id: number;
sha: string;
ref: string;
status: string;
export interface PipelineSchemaCamelized extends PipelineBase {
createdAt: Date;
updatedAt: Date;
webUrl: string;
Expand Down Expand Up @@ -67,12 +78,6 @@ export class Pipelines extends BaseService {
return RequestHelper.post(this, `projects/${pId}/pipelines/${pipelineId}/cancel`, options);
}

showJobs(projectId: string | number, pipelineId: number, options?: { scope: JobScope } & Sudo) {
const pId = encodeURIComponent(projectId);

return RequestHelper.get(this, `projects/${pId}/pipelines/${pipelineId}/jobs`, options);
}

allVariables(projectId: string | number, pipelineId: number, options?: PaginatedRequestOptions) {
const [pId, pipeId] = [projectId, pipelineId].map(encodeURIComponent);

Expand Down
9 changes: 9 additions & 0 deletions packages/gitbeaker-core/test/mocks/requesterFn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { RequesterType } from '@gitbeaker/requester-utils';

export const mockRequesterFn = () =>
({
get: jest.fn(() => Promise.resolve([])),
post: jest.fn(() => Promise.resolve({})),
put: jest.fn(() => Promise.resolve({})),
delete: jest.fn(() => Promise.resolve({})),
} as RequesterType);
2 changes: 1 addition & 1 deletion packages/gitbeaker-core/test/unit/bundles/Gitlab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as Services from '../../../src/services';
describe('Instantiating All services', () => {
it('should create a valid gitlab service object using import', async () => {
const bundle = new Gitlab({
requester: {},
requesterFn: () => ({}),
token: 'abcdefg',
});

Expand Down
4 changes: 2 additions & 2 deletions packages/gitbeaker-core/test/unit/bundles/GroupsBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GroupsBundle } from '../../../src';
import * as Services from '../../../src/services';

test('All the correct service keys are included in the groups bundle', async () => {
const bundle: GroupsBundle = new GroupsBundle({ requester: {}, token: 'test' });
const bundle: GroupsBundle = new GroupsBundle({ requesterFn: () => ({}), token: 'test' });
const services = [
'Groups',
'GroupAccessRequests',
Expand All @@ -24,7 +24,7 @@ test('All the correct service keys are included in the groups bundle', async ()
});

test('All the correct service instances are included in the groups bundle', async () => {
const bundle = new GroupsBundle({ requester: {}, token: 'test' });
const bundle = new GroupsBundle({ requesterFn: () => ({}), token: 'test' });

(Object.keys(bundle) as (keyof typeof bundle)[]).forEach((key) => {
expect(bundle[key]).toBeInstanceOf(Services[key]);
Expand Down
4 changes: 2 additions & 2 deletions packages/gitbeaker-core/test/unit/bundles/ProjectsBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ProjectsBundle } from '../../../src';
import * as Services from '../../../src/services';

test('All the correct service keys are included in the projects bundle', async () => {
const bundle: ProjectsBundle = new ProjectsBundle({ requester: {}, token: 'test' });
const bundle: ProjectsBundle = new ProjectsBundle({ requesterFn: () => ({}), token: 'test' });
const services = [
'Branches',
'Commits',
Expand Down Expand Up @@ -51,7 +51,7 @@ test('All the correct service keys are included in the projects bundle', async (
});

test('All the correct service instances are included in the projects bundle', async () => {
const bundle = new ProjectsBundle({ requester: {}, token: 'test' });
const bundle = new ProjectsBundle({ requesterFn: () => ({}), token: 'test' });

(Object.keys(bundle) as (keyof typeof bundle)[]).forEach((key) => {
expect(bundle[key]).toBeInstanceOf(Services[key]);
Expand Down
4 changes: 2 additions & 2 deletions packages/gitbeaker-core/test/unit/bundles/UsersBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { UsersBundle } from '../../../src';
import * as Services from '../../../src/services';

test('All the correct service keys are included in the users bundle', async () => {
const bundle: UsersBundle = new UsersBundle({ requester: {}, token: 'test' });
const bundle: UsersBundle = new UsersBundle({ requesterFn: () => ({}), token: 'test' });
const services = [
'Users',
'UserEmails',
Expand All @@ -16,7 +16,7 @@ test('All the correct service keys are included in the users bundle', async () =
});

test('All the correct service instances are included in the users bundle', async () => {
const bundle = new UsersBundle({ requester: {}, token: 'test' });
const bundle = new UsersBundle({ requesterFn: () => ({}), token: 'test' });

(Object.keys(bundle) as (keyof typeof bundle)[]).forEach((key) => {
expect(bundle[key]).toBeInstanceOf(Services[key]);
Expand Down
Loading

0 comments on commit 565bd15

Please sign in to comment.