Skip to content

Commit

Permalink
chore(middleware): abstract all middleware builder functions
Browse files Browse the repository at this point in the history
- refactor code to abstract the auth middleware
- refactor code to abstract the http middleware
- write test for the new refactored code
  • Loading branch information
ajimae committed Jun 24, 2021
1 parent fef8a4a commit c071a2c
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 1 deletion.
55 changes: 55 additions & 0 deletions packages/sdk-client/src/builder/ApiRootBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { ApiRoot } from '@commercetools/platform-sdk'
import { Middleware, AuthMiddlewareOptions, HttpMiddlewareOptions } from '../types/sdk'
import { default as createClient } from '../sdk-client/client'
import { default as createHttpClient } from '../sdk-middleware-http/http'
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk'
import { default as createAuthForClientCredentialsFlow } from '../sdk-middleware-auth/client-credentials-flow'

export default class ApiRootBuilder {
private projectKey: string | undefined
private middlewares: Array<Middleware> = []

withProjectKey(key: string): ApiRootBuilder {
this.projectKey = key;
return this;
}

withAuthMiddleware(options: AuthMiddlewareOptions): ApiRootBuilder {
const authMiddleware = createAuthForClientCredentialsFlow({
...options,
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
projectKey: this.projectKey || options.projectKey,
credentials: {
clientId: options.credentials.clientId || '',
clientSecret: options.credentials.clientSecret || '',
},
oauthUri: options.oauthUri || '',
scopes: options.scopes,
fetch: options.fetch,
})

// TODO: add other authMiddleware and add to middlewares list

this.middlewares.push(authMiddleware);
return this;
}

withHttpMiddleware(options: HttpMiddlewareOptions): ApiRootBuilder {
// TODO: check to make sure authMiddleware has been added before adding this middleware
const httpMiddleware = createHttpClient({
...options,
host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
fetch: options.fetch,
})

this.middlewares.push(httpMiddleware);
return this;
}

// TODO: add other middleware builder functions

build(): ApiRoot {
const { middlewares } = this;
return createApiBuilderFromCtpClient(createClient({ middlewares }));
}
}
1 change: 1 addition & 0 deletions packages/sdk-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ export { default as createHttpClient } from './sdk-middleware-http/http'
// export { createApiBuilderFromCtpClient } from '../../platform-sdk/src/index' // import directly from project structure.
// export { createApiBuilderFromCtpClient } from '@commercetools/typescript-sdk'
export { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk'
export { default as ApiRootBuilder } from './builder/ApiRootBuilder';
2 changes: 1 addition & 1 deletion packages/sdk-client/src/types/sdk.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export type Middleware = (next: Dispatch) => Dispatch

export interface ClientRequest {
baseUri?: string
uri?: string
uri: string
headers?: VariableMap
method: MethodType
uriTemplate?: string
Expand Down
97 changes: 97 additions & 0 deletions packages/sdk-client/test/builder.test/client-builder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import ApiRootBuilder from "../../src/builder/ApiRootBuilder";
require("dotenv").config();

export const projectKey = 'demo-1';
const fetch = require("node-fetch");

describe('client builder', () => {
let apiRoot;
const rand = Math.floor(Math.random() * 9999);
const customerSampleData = {
firstName: "test2",
lastName: "test",
email: `test-${rand}@test.com`,
password: "123",
key: "test" + rand,
countryCode: "DE",
};

const createCustomerDraft = (customerData) => {
const {
email,
password,
firstName,
lastName,
countryCode,
key,
} = customerData;
return {
email,
password,
key,
firstName,
lastName,
addresses: [
{
country: countryCode,
},
],
defaultShippingAddress: 0,
};
};

const authMiddlewareOptions = {
host: 'https://auth.europe-west1.gcp.commercetools.com',
projectKey: process.env.PROJECT_KEY || projectKey,
credentials: {
clientId: process.env.adminClientId || '',
clientSecret: process.env.adminClientSecret || '',
},
oauthUri: process.env.adminAuthUrl || '',
scopes: ['manage_project:demo-1'],
fetch,
};

const httpMiddlewareOptions = {
host: 'https://api.europe-west1.gcp.commercetools.com',
fetch
}

apiRoot = new ApiRootBuilder()
.withAuthMiddleware(authMiddlewareOptions)
.withHttpMiddleware(httpMiddlewareOptions)
.build();

test('get bare project details', async () => {
const projectDetails = await apiRoot
.withProjectKey({ projectKey })
.get()
.execute();

expect(projectDetails).toHaveProperty('body');
expect(projectDetails.body).toHaveProperty('name');
expect(projectDetails.body).toHaveProperty('carts');
expect(projectDetails.body).toHaveProperty('shoppingLists');

expect(projectDetails.body.key).toEqual(projectKey);
})

test('create a customer', async () => {
const customer = await apiRoot
.withProjectKey({ projectKey })
.customers()
.post({
body: createCustomerDraft(customerSampleData),
}).execute();

console.log(customer, ">>>>>")
expect(customer).toHaveProperty('body');
expect(customer).toHaveProperty('statusCode');
expect(customer.body.customer).toHaveProperty('id');
expect(customer.body.customer).toHaveProperty('email');

expect(customer.body.customer.firstName).toEqual('test2');
expect(customer.body.customer.lastName).toEqual('test');
expect(customer.body.customer.email).toEqual(`test-${rand}@test.com`);
})
})

0 comments on commit c071a2c

Please sign in to comment.