Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes/presales #91

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,12 @@ application-templates/**/yarn.lock
application-templates/starter-typescript/job/.env
application-templates/starter-typescript/job/.env.*
!application-templates/starter-typescript/job/.env.example
application-templates/typescript/event/.env
application-templates/typescript/event/.env.*
!application-templates/typescript/event/.env.example
application-templates/typescript/service/.env
application-templates/typescript/service/.env.*
!application-templates/typescript/service/.env.example

#IDE
.idea
9 changes: 6 additions & 3 deletions application-templates/typescript/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ coverage
.terraform
*.tfstate*
*.tfvars

.yarn
.DS_Store
.vscode
.idea
build/
.env
public/
!.env
.env.local
public/
.connect
2 changes: 2 additions & 0 deletions application-templates/typescript/event/jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module.exports = {
displayName: 'Tests Typescript Application - Event',
moduleDirectories: ['node_modules', 'src'],
testMatch: ['**/tests/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
testPathIgnorePatterns: ['tests/setup-tests.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
setupFiles: ['<rootDir>/tests/setup-tests.ts'],
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import {
} from '@commercetools/platform-sdk';
import { ByProjectKeyRequestBuilder } from '@commercetools/platform-sdk/dist/declarations/src/generated/client/by-project-key-request-builder';

const CUSTOMER_CREATE_SUBSCRIPTION_KEY =
'myconnector-customerCreateSubscription';
const SUBSCRIPTION_KEY = 'myconnector-customerCreateSubscription';

export async function createGcpPubSubCustomerCreateSubscription(
export async function createGcpPubSubSubscription(
apiRoot: ByProjectKeyRequestBuilder,
topicName: string,
projectId: string
Expand All @@ -21,7 +20,7 @@ export async function createGcpPubSubCustomerCreateSubscription(
await createSubscription(apiRoot, destination);
}

export async function createAzureServiceBusCustomerCreateSubscription(
export async function createAzureServiceBusSubscription(
apiRoot: ByProjectKeyRequestBuilder,
connectionString: string
): Promise<void> {
Expand All @@ -36,12 +35,12 @@ async function createSubscription(
apiRoot: ByProjectKeyRequestBuilder,
destination: Destination
) {
await deleteCustomerCreateSubscription(apiRoot);
await deleteSubscription(apiRoot);
await apiRoot
.subscriptions()
.post({
body: {
key: CUSTOMER_CREATE_SUBSCRIPTION_KEY,
key: SUBSCRIPTION_KEY,
destination,
messages: [
{
Expand All @@ -54,7 +53,7 @@ async function createSubscription(
.execute();
}

export async function deleteCustomerCreateSubscription(
export async function deleteSubscription(
apiRoot: ByProjectKeyRequestBuilder
): Promise<void> {
const {
Expand All @@ -63,7 +62,7 @@ export async function deleteCustomerCreateSubscription(
.subscriptions()
.get({
queryArgs: {
where: `key = "${CUSTOMER_CREATE_SUBSCRIPTION_KEY}"`,
where: `key = "${SUBSCRIPTION_KEY}"`,
},
})
.execute();
Expand All @@ -73,7 +72,7 @@ export async function deleteCustomerCreateSubscription(

await apiRoot
.subscriptions()
.withKey({ key: CUSTOMER_CREATE_SUBSCRIPTION_KEY })
.withKey({ key: SUBSCRIPTION_KEY })
.delete({
queryArgs: {
version: subscription.version,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ dotenv.config();
import { createApiRoot } from '../client/create.client';
import { assertError, assertString } from '../utils/assert.utils';
import {
createAzureServiceBusCustomerCreateSubscription,
createGcpPubSubCustomerCreateSubscription,
createAzureServiceBusSubscription,
createGcpPubSubSubscription,
} from './actions';

const CONNECT_GCP_TOPIC_NAME_KEY = 'CONNECT_GCP_TOPIC_NAME';
Expand All @@ -24,22 +24,15 @@ async function postDeploy(properties: Map<string, unknown>): Promise<void> {
CONNECT_AZURE_CONNECTION_STRING_KEY
);
assertString(connectionString, CONNECT_AZURE_CONNECTION_STRING_KEY);
await createAzureServiceBusCustomerCreateSubscription(
apiRoot,
connectionString
);
await createAzureServiceBusSubscription(apiRoot, connectionString);
break;
}
default: {
const topicName = properties.get(CONNECT_GCP_TOPIC_NAME_KEY);
const projectId = properties.get(CONNECT_GCP_PROJECT_ID_KEY);
assertString(topicName, CONNECT_GCP_TOPIC_NAME_KEY);
assertString(projectId, CONNECT_GCP_PROJECT_ID_KEY);
await createGcpPubSubCustomerCreateSubscription(
apiRoot,
topicName,
projectId
);
await createGcpPubSubSubscription(apiRoot, topicName, projectId);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ dotenv.config();

import { createApiRoot } from '../client/create.client';
import { assertError } from '../utils/assert.utils';
import { deleteCustomerCreateSubscription } from './actions';
import { deleteSubscription } from './actions';

async function preUndeploy(): Promise<void> {
const apiRoot = createApiRoot();
await deleteCustomerCreateSubscription(apiRoot);
await deleteSubscription(apiRoot);
}

async function run(): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Request, Response } from 'express';
import { createApiRoot } from '../client/create.client';
import CustomError from '../errors/custom.error';
import { logger } from '../utils/logger.utils';
import { Message } from '@commercetools/platform-sdk';

/**
* Exposed event POST endpoint.
Expand Down Expand Up @@ -36,9 +37,13 @@ export const post = async (request: Request, response: Response) => {
: undefined;

if (decodedData) {
const jsonData = JSON.parse(decodedData);
const jsonData: Message | null = JSON.parse(decodedData);

customerId = jsonData.customer.id;
if (jsonData) {
if (jsonData.type === 'CustomerCreated') {
customerId = jsonData.customer.id;
}
}
}

if (!customerId) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { describe, expect } from '@jest/globals';
import { CustomerCreatedMessage, Customer } from '@commercetools/platform-sdk';
import request from 'supertest';
import app from '../../src/app';
import { createApiRoot } from '../../src/client/create.client';
import { readConfiguration } from '../../src/utils/config.utils';

jest.mock('../../src/client/create.client', () => {
const mockCreateApiRoot = jest.fn();
return {
createApiRoot: mockCreateApiRoot,
};
});
jest.mock('../../src/utils/config.utils');

const customerId = 'd93a8493-1bfd-4e2d-8b46-20a765dd0978';

const customer: Customer = {
id: customerId,
createdAt: '',
lastModifiedAt: '',
version: 0,
email: '',
isEmailVerified: true,
addresses: [],
authenticationMode: 'Password',
};

const orderCreatedMessage: CustomerCreatedMessage = {
createdAt: '',
id: '',
lastModifiedAt: '',
resource: { id: customerId, typeId: 'customer' },
resourceVersion: 0,
sequenceNumber: 0,
type: 'CustomerCreated',
version: 0,
customer: customer,
};

describe('Testing Event Controller', () => {
beforeEach(() => {
(readConfiguration as jest.Mock).mockClear();
});
test('Customer Created (Mocked)', async () => {
// Define a mock root to be returned
const withId = jest.fn().mockReturnValueOnce({
get: jest.fn().mockReturnValueOnce({
execute: jest.fn().mockReturnValueOnce(customer),
}),
});
const mockRoot = {
customers: jest.fn().mockReturnValueOnce({
withId: withId,
}),
};

// Set the mock implementation for createApiRoot to return mockRoot
(createApiRoot as jest.Mock).mockReturnValueOnce(mockRoot);

const response = await request(app)
.post('/event')
.send({
message: {
data: Buffer.from(JSON.stringify(orderCreatedMessage)).toString(
'base64'
),
},
});
expect(response.status).toBe(204);
expect(withId).toHaveBeenCalledWith({ ID: customerId });
});

/*
* This Test really calls the commercetools APIs. To do so,
* - remove the mocking code in line 8-14
* - configure a "real" customerId
* - remove the skip below
*
* The code below comes in handy to test during development.
*/
it.skip('Customer Created', async () => {
const response = await request(app)
.post('/event')
.send({
message: {
data: Buffer.from(JSON.stringify(orderCreatedMessage)).toString(
'base64'
),
},
});
expect(response.status).toBe(204);
});
});
3 changes: 3 additions & 0 deletions application-templates/typescript/event/tests/setup-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { config } from 'dotenv';
config();
config({ path: `.env.local`, override: true });
2 changes: 1 addition & 1 deletion application-templates/typescript/event/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"extends": "@tsconfig/recommended/tsconfig.json",
"exclude": ["node_modules", "**/*.spec.ts"],
"exclude": ["node_modules", "**/*.spec.ts", "**/setup-tests.ts"],
"compilerOptions": {
"resolveJsonModule": true,
"outDir": "./build",
Expand Down
2 changes: 2 additions & 0 deletions application-templates/typescript/service/jest.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module.exports = {
displayName: 'Tests Typescript Application - Service',
moduleDirectories: ['node_modules', 'src'],
testMatch: ['**/tests/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
testPathIgnorePatterns: ['tests/setup-tests.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
setupFiles: ['<rootDir>/tests/setup-tests.ts'],
};
2 changes: 2 additions & 0 deletions application-templates/typescript/service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"@types/express": "^4.17.14",
"@types/jest": "^29.0.3",
"@types/node": "^18.7.18",
"@types/supertest": "^6.0.2",
"@types/validator": "^13.7.10",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
Expand All @@ -32,6 +33,7 @@
"nodemon": "^3.0.1",
"prettier": "^3.0.1",
"rimraf": "^5.0.1",
"supertest": "^7.0.0",
"ts-jest": "^29.1.1",
"typescript": "^5.1.6"
},
Expand Down
Loading
Loading