@labdigital/commercetools-mock 0.5.16 → 0.5.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,8 @@ import { AbstractStorage } from '../storage';
4
4
  export declare type QueryParams = {
5
5
  expand?: string[];
6
6
  where?: string[];
7
+ offset?: number;
8
+ limit?: number;
7
9
  };
8
10
  export declare type GetParams = {
9
11
  expand?: string[];
@@ -3,4 +3,5 @@ import { AbstractResourceRepository } from './abstract';
3
3
  export declare class CustomerRepository extends AbstractResourceRepository {
4
4
  getTypeId(): ReferenceTypeId;
5
5
  create(projectKey: string, draft: CustomerDraft): Customer;
6
+ getMe(projectKey: string): Customer | undefined;
6
7
  }
@@ -1,4 +1,4 @@
1
- import { Payment, PaymentAddTransactionAction, PaymentDraft, PaymentSetCustomFieldAction, PaymentSetCustomTypeAction, ReferenceTypeId, TransactionDraft } from '@commercetools/platform-sdk';
1
+ import { Payment, PaymentAddTransactionAction, PaymentChangeTransactionStateAction, PaymentDraft, PaymentSetCustomFieldAction, PaymentSetCustomTypeAction, PaymentTransitionStateAction, ReferenceTypeId, TransactionDraft } from '@commercetools/platform-sdk';
2
2
  import { AbstractResourceRepository } from './abstract';
3
3
  import { Writable } from '../types';
4
4
  export declare class PaymentRepository extends AbstractResourceRepository {
@@ -17,5 +17,7 @@ export declare class PaymentRepository extends AbstractResourceRepository {
17
17
  setCustomField: (projectKey: string, resource: Payment, { name, value }: PaymentSetCustomFieldAction) => void;
18
18
  setCustomType: (projectKey: string, resource: Writable<Payment>, { type, fields }: PaymentSetCustomTypeAction) => void;
19
19
  addTransaction: (projectKey: string, resource: Writable<Payment>, { transaction }: PaymentAddTransactionAction) => void;
20
+ changeTransactionState: (_projectKey: string, resource: Writable<Payment>, { transactionId, state }: PaymentChangeTransactionStateAction) => void;
21
+ transitionState: (projectKey: string, resource: Writable<Payment>, { state }: PaymentTransitionStateAction) => void;
20
22
  };
21
23
  }
@@ -0,0 +1,12 @@
1
+ import AbstractService from './abstract';
2
+ import { Request, Response, Router } from 'express';
3
+ import { AbstractStorage } from '../storage';
4
+ import { CustomerRepository } from '../repositories/customer';
5
+ export declare class MyCustomerService extends AbstractService {
6
+ repository: CustomerRepository;
7
+ constructor(parent: Router, storage: AbstractStorage);
8
+ getBasePath(): string;
9
+ registerRoutes(parent: Router): void;
10
+ getMe(request: Request, response: Response): Response<any, Record<string, any>>;
11
+ signUp(request: Request, response: Response): Response<any, Record<string, any>>;
12
+ }
@@ -1,9 +1,10 @@
1
1
  import { ShippingMethodRepository } from '../repositories/shipping-method';
2
2
  import AbstractService from './abstract';
3
- import { Router } from 'express';
4
3
  import { AbstractStorage } from '../storage';
4
+ import { Router } from 'express';
5
5
  export declare class ShippingMethodService extends AbstractService {
6
6
  repository: ShippingMethodRepository;
7
7
  constructor(parent: Router, storage: AbstractStorage);
8
8
  getBasePath(): string;
9
+ extraRoutes(parent: Router): void;
9
10
  }
package/dist/types.d.ts CHANGED
@@ -18,7 +18,7 @@ export declare type Writable<T> = {
18
18
  -readonly [P in keyof T]: Writable<T[P]>;
19
19
  };
20
20
  export declare type RepositoryTypes = ReferenceTypeId | 'product-projection';
21
- export declare type ServiceTypes = RepositoryTypes | 'my-cart' | 'my-payment';
21
+ export declare type ServiceTypes = RepositoryTypes | 'my-cart' | 'my-payment' | 'my-customer';
22
22
  export declare type Services = Partial<{
23
23
  [index in ServiceTypes]: AbstractService;
24
24
  }>;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.5.16",
2
+ "version": "0.5.19",
3
3
  "license": "MIT",
4
4
  "main": "dist/index.js",
5
5
  "typings": "dist/index.d.ts",
@@ -17,9 +17,7 @@
17
17
  "build": "tsdx build --target=node",
18
18
  "test": "tsdx test",
19
19
  "lint": "tsdx lint",
20
- "prepare": "tsdx build",
21
- "size": "size-limit",
22
- "analyze": "size-limit --why"
20
+ "prepare": "tsdx build"
23
21
  },
24
22
  "prettier": {
25
23
  "printWidth": 80,
@@ -30,19 +28,8 @@
30
28
  "name": "@labdigital/commercetools-mock",
31
29
  "author": "Michael van Tellingen",
32
30
  "module": "dist/commercetools--mock.esm.js",
33
- "size-limit": [
34
- {
35
- "path": "dist/commercetools--mock.cjs.production.min.js",
36
- "limit": "10 KB"
37
- },
38
- {
39
- "path": "dist/commercetools--mock.esm.js",
40
- "limit": "10 KB"
41
- }
42
- ],
43
31
  "devDependencies": {
44
32
  "@babel/preset-typescript": "^7.16.7",
45
- "@size-limit/preset-small-lib": "^7.0.5",
46
33
  "@types/basic-auth": "^1.1.3",
47
34
  "@types/deep-equal": "^1.0.1",
48
35
  "@types/express": "^4.17.13",
@@ -53,7 +40,6 @@
53
40
  "got": "^11.8.3",
54
41
  "husky": "^7.0.4",
55
42
  "nodemon": "^2.0.15",
56
- "size-limit": "^7.0.5",
57
43
  "ts-node": "^10.4.0",
58
44
  "tsdx": "^0.14.1",
59
45
  "tslib": "^2.3.1",
package/src/ctMock.ts CHANGED
@@ -37,6 +37,7 @@ import { SubscriptionService } from './services/subscription'
37
37
  import { TaxCategoryService } from './services/tax-category'
38
38
  import { TypeService } from './services/type'
39
39
  import { ZoneService } from './services/zone'
40
+ import { MyCustomerService } from './services/my-customer'
40
41
 
41
42
  export type CommercetoolsMockOptions = {
42
43
  validateCredentials: boolean
@@ -163,6 +164,7 @@ export class CommercetoolsMock {
163
164
  order: new OrderService(projectRouter, this._storage),
164
165
  payment: new PaymentService(projectRouter, this._storage),
165
166
  'my-cart': new MyCartService(projectRouter, this._storage),
167
+ 'my-customer': new MyCustomerService(projectRouter, this._storage),
166
168
  'my-payment': new MyPaymentService(projectRouter, this._storage),
167
169
  'shipping-method': new ShippingMethodService(
168
170
  projectRouter,
@@ -14,6 +14,8 @@ import { CommercetoolsError } from '../exceptions'
14
14
  export type QueryParams = {
15
15
  expand?: string[]
16
16
  where?: string[]
17
+ offset?: number
18
+ limit?: number
17
19
  }
18
20
 
19
21
  export type GetParams = {
@@ -69,6 +71,8 @@ export abstract class AbstractResourceRepository extends AbstractRepository {
69
71
  return this._storage.query(projectKey, this.getTypeId(), {
70
72
  expand: params.expand,
71
73
  where: params.where,
74
+ offset: params.offset,
75
+ limit: params.limit,
72
76
  })
73
77
  }
74
78
 
@@ -30,6 +30,7 @@ export class CategoryRepository extends AbstractResourceRepository {
30
30
  name: draft.name,
31
31
  slug: draft.slug,
32
32
  orderHint: draft.orderHint || '',
33
+ externalId: draft.externalId || '',
33
34
  parent: draft.parent
34
35
  ? { typeId: 'category', id: draft.parent.id! }
35
36
  : undefined,
@@ -14,11 +14,19 @@ export class CustomerRepository extends AbstractResourceRepository {
14
14
  const resource: Customer = {
15
15
  ...getBaseResourceProperties(),
16
16
  email: draft.email,
17
- password: draft.password,
17
+ password: Buffer.from(draft.password).toString('base64'),
18
18
  isEmailVerified: draft.isEmailVerified || false,
19
19
  addresses: [],
20
20
  }
21
21
  this.save(projectKey, resource)
22
22
  return resource
23
23
  }
24
+ getMe(projectKey: string): Customer | undefined {
25
+ const results = this._storage.query(projectKey, this.getTypeId(), {}) // grab the first customer you can find
26
+ if (results.count > 0) {
27
+ return results.results[0] as Customer
28
+ }
29
+
30
+ return
31
+ }
24
32
  }
@@ -25,7 +25,6 @@ export class DiscountCodeRepository extends AbstractResourceRepository {
25
25
  }
26
26
 
27
27
  create(projectKey: string, draft: DiscountCodeDraft): DiscountCode {
28
- console.log(draft)
29
28
  const resource: DiscountCode = {
30
29
  ...getBaseResourceProperties(),
31
30
  applicationVersion: 1,
@@ -1,11 +1,15 @@
1
1
  import {
2
2
  Payment,
3
3
  PaymentAddTransactionAction,
4
+ PaymentChangeTransactionStateAction,
4
5
  PaymentDraft,
5
6
  PaymentSetCustomFieldAction,
6
7
  PaymentSetCustomTypeAction,
8
+ PaymentTransitionStateAction,
7
9
  ReferenceTypeId,
10
+ State,
8
11
  StateReference,
12
+ Transaction,
9
13
  TransactionDraft,
10
14
  } from '@commercetools/platform-sdk'
11
15
  import { AbstractResourceRepository } from './abstract'
@@ -111,10 +115,43 @@ export class PaymentRepository extends AbstractResourceRepository {
111
115
  this.transactionFromTransactionDraft(transaction, projectKey),
112
116
  ]
113
117
  },
118
+ changeTransactionState: (
119
+ _projectKey: string,
120
+ resource: Writable<Payment>,
121
+ { transactionId, state }: PaymentChangeTransactionStateAction
122
+ ) => {
123
+ const index = resource.transactions.findIndex(
124
+ (e: Transaction) => e.id === transactionId
125
+ )
126
+ const updatedTransaction: Transaction = {
127
+ ...resource.transactions[index],
128
+ state,
129
+ }
130
+ resource.transactions[index] = updatedTransaction
131
+ },
132
+ transitionState: (
133
+ projectKey: string,
134
+ resource: Writable<Payment>,
135
+ { state }: PaymentTransitionStateAction
136
+ ) => {
137
+ const stateObj = this._storage.getByResourceIdentifier(
138
+ projectKey,
139
+ state
140
+ ) as State | null
141
+
142
+ if (!stateObj) {
143
+ throw new Error(`State ${state} not found`)
144
+ }
145
+
146
+ resource.paymentStatus.state = {
147
+ typeId: 'state',
148
+ id: stateObj.id,
149
+ obj: stateObj,
150
+ }
151
+ },
114
152
  // addInterfaceInteraction: () => {},
115
153
  // changeAmountPlanned: () => {},
116
154
  // changeTransactionInteractionId: () => {},
117
- // changeTransactionState: () => {},
118
155
  // changeTransactionTimestamp: () => {},
119
156
  // setAmountPaid: () => {},
120
157
  // setAmountRefunded: () => {},
@@ -129,6 +166,5 @@ export class PaymentRepository extends AbstractResourceRepository {
129
166
  // setMethodInfoName: () => {},
130
167
  // setStatusInterfaceCode: () => {},
131
168
  // setStatusInterfaceText: () => {},
132
- // transitionState: () => {},
133
169
  }
134
170
  }
@@ -55,6 +55,8 @@ export class ProductProjectionRepository extends AbstractResourceRepository {
55
55
 
56
56
  const results = this._storage.query(projectKey, this.getTypeId(), {
57
57
  where: wherePredicate,
58
+ offset: query.offset ? Number(query.offset) : undefined,
59
+ limit: query.limit ? Number(query.limit) : undefined,
58
60
  }) //TODO: this is a partial implementation, but I don't really have the time to implement an actual search API right now
59
61
 
60
62
  return results
@@ -146,7 +146,6 @@ export class ProjectRepository extends AbstractRepository {
146
146
  resource: Writable<Project>,
147
147
  { cartsConfiguration }: ProjectChangeCartsConfigurationAction
148
148
  ) => {
149
- console.log(cartsConfiguration)
150
149
  resource.carts = cartsConfiguration || {
151
150
  countryTaxRateFallbackEnabled: false,
152
151
  deleteDaysAfterLastModification: 90,
@@ -37,9 +37,14 @@ export default abstract class AbstractService {
37
37
  }
38
38
 
39
39
  get(request: Request, response: Response) {
40
+ const limit = this._parseParam(request.query.limit)
41
+ const offset = this._parseParam(request.query.offset)
42
+
40
43
  const result = this.repository.query(request.params.projectKey, {
41
44
  expand: this._parseParam(request.query.expand),
42
45
  where: this._parseParam(request.query.where),
46
+ limit: limit !== undefined ? Number(limit) : undefined,
47
+ offset: offset !== undefined ? Number(offset) : undefined,
43
48
  })
44
49
  return response.status(200).send(result)
45
50
  }
@@ -49,7 +54,6 @@ export default abstract class AbstractService {
49
54
  if (!result) {
50
55
  return response.status(404).send()
51
56
  }
52
- console.log(JSON.stringify(result, null, 4))
53
57
  return response.status(200).send(result)
54
58
  }
55
59
 
@@ -0,0 +1,51 @@
1
+ import { MyCustomerDraft } from '@commercetools/platform-sdk'
2
+ import supertest from 'supertest'
3
+ import { CommercetoolsMock } from '../index'
4
+
5
+ const ctMock = new CommercetoolsMock()
6
+
7
+ describe('Me', () => {
8
+ afterEach(() => {
9
+ ctMock.clear()
10
+ })
11
+
12
+ test('Create me', async () => {
13
+ const draft: MyCustomerDraft = {
14
+ email: 'test@example.org',
15
+ password: 'p4ssw0rd',
16
+ }
17
+
18
+ const response = await supertest(ctMock.app)
19
+ .post('/dummy/me/signup')
20
+ .send(draft)
21
+
22
+ expect(response.status).toBe(201)
23
+ expect(response.body).toEqual({
24
+ customer: {
25
+ ...draft,
26
+ password: 'cDRzc3cwcmQ=',
27
+ version: 1,
28
+ isEmailVerified: false,
29
+ addresses: [],
30
+ id: expect.anything(),
31
+ createdAt: expect.anything(),
32
+ lastModifiedAt: expect.anything(),
33
+ },
34
+ })
35
+ })
36
+
37
+ test('Get me', async () => {
38
+ const draft: MyCustomerDraft = {
39
+ email: 'test@example.org',
40
+ password: 'p4ssw0rd',
41
+ }
42
+ const createResponse = await supertest(ctMock.app)
43
+ .post('/dummy/me/signup')
44
+ .send(draft)
45
+
46
+ const response = await supertest(ctMock.app).get(`/dummy/me`)
47
+
48
+ expect(response.status).toBe(200)
49
+ expect(response.body).toEqual(createResponse.body.customer)
50
+ })
51
+ })
@@ -0,0 +1,46 @@
1
+ import AbstractService from './abstract'
2
+ import { Request, Response, Router } from 'express'
3
+ import { AbstractStorage } from '../storage'
4
+ import { CustomerRepository } from '../repositories/customer'
5
+
6
+ export class MyCustomerService extends AbstractService {
7
+ public repository: CustomerRepository
8
+
9
+ constructor(parent: Router, storage: AbstractStorage) {
10
+ super(parent)
11
+ this.repository = new CustomerRepository(storage)
12
+ }
13
+
14
+ getBasePath() {
15
+ return 'me'
16
+ }
17
+
18
+ registerRoutes(parent: Router) {
19
+ // Overwrite this function to be able to handle /me path.
20
+ const basePath = this.getBasePath()
21
+ const router = Router({ mergeParams: true })
22
+
23
+ this.extraRoutes(router)
24
+
25
+ router.get('', this.getMe.bind(this))
26
+
27
+ router.post('/signup', this.signUp.bind(this))
28
+
29
+ parent.use(`/${basePath}`, router)
30
+ }
31
+
32
+ getMe(request: Request, response: Response) {
33
+ const resource = this.repository.getMe(request.params.projectKey)
34
+ if (!resource) {
35
+ return response.status(404).send('Not found')
36
+ }
37
+ return response.status(200).send(resource)
38
+ }
39
+
40
+ signUp(request: Request, response: Response) {
41
+ const draft = request.body
42
+ const resource = this.repository.create(request.params.projectKey, draft)
43
+ const result = this._expandWithId(request, resource.id)
44
+ return response.status(this.createStatusCode).send({ customer: result })
45
+ }
46
+ }
@@ -118,6 +118,26 @@ describe('Product Projection Search', () => {
118
118
  })
119
119
  })
120
120
 
121
+ test('Search product projection page 2', async () => {
122
+ const response = await supertest(ctMock.app).get(
123
+ '/dummy/product-projections/search?' +
124
+ qs.stringify({
125
+ filter: ['masterVariant.sku:"1337"'],
126
+ limit: 50,
127
+ offset: 100,
128
+ })
129
+ )
130
+
131
+ const projection: ProductProjection = response.body
132
+ expect(projection).toEqual({
133
+ count: 1,
134
+ limit: 50,
135
+ offset: 100,
136
+ total: 0,
137
+ results: [],
138
+ })
139
+ })
140
+
121
141
  test('Search product projection with query.filter', async () => {
122
142
  const response = await supertest(ctMock.app).get(
123
143
  '/dummy/product-projections/search?' +
@@ -72,4 +72,31 @@ describe('Shipping method', () => {
72
72
  expect(response.status).toBe(200)
73
73
  expect(response.body).toEqual(createResponse.body)
74
74
  })
75
+
76
+ test('Get shipping methods matching cart', async () => {
77
+ const draft: ShippingMethodDraft = {
78
+ name: 'foo',
79
+ taxCategory: { typeId: 'tax-category', key: 'standard' },
80
+ isDefault: true,
81
+ zoneRates: [],
82
+ }
83
+ const createResponse = await supertest(ctMock.app)
84
+ .post('/dummy/shipping-methods')
85
+ .send(draft)
86
+
87
+ expect(createResponse.status).toBe(201)
88
+
89
+ const response = await supertest(ctMock.app).get(
90
+ `/dummy/shipping-methods/matching-cart?cartId=fake-cart-id`
91
+ )
92
+
93
+ expect(response.status).toBe(200)
94
+ expect(response.body).toEqual({
95
+ count: 1,
96
+ limit: 20,
97
+ offset: 0,
98
+ results: [createResponse.body],
99
+ total: 1,
100
+ })
101
+ })
75
102
  })
@@ -1,7 +1,7 @@
1
1
  import { ShippingMethodRepository } from '../repositories/shipping-method'
2
2
  import AbstractService from './abstract'
3
- import { Router } from 'express'
4
3
  import { AbstractStorage } from '../storage'
4
+ import { Request, Response, Router } from 'express'
5
5
 
6
6
  export class ShippingMethodService extends AbstractService {
7
7
  public repository: ShippingMethodRepository
@@ -9,9 +9,14 @@ export class ShippingMethodService extends AbstractService {
9
9
  constructor(parent: Router, storage: AbstractStorage) {
10
10
  super(parent)
11
11
  this.repository = new ShippingMethodRepository(storage)
12
+ this.registerRoutes(parent)
12
13
  }
13
14
 
14
15
  getBasePath() {
15
16
  return 'shipping-methods'
16
17
  }
18
+
19
+ extraRoutes(parent: Router) {
20
+ parent.get('/matching-cart', this.get.bind(this))
21
+ }
17
22
  }
package/src/types.ts CHANGED
@@ -18,7 +18,11 @@ import { TaxCategoryRepository } from './repositories/tax-category'
18
18
  export type Writable<T> = { -readonly [P in keyof T]: Writable<T[P]> }
19
19
 
20
20
  export type RepositoryTypes = ReferenceTypeId | 'product-projection'
21
- export type ServiceTypes = RepositoryTypes | 'my-cart' | 'my-payment'
21
+ export type ServiceTypes =
22
+ | RepositoryTypes
23
+ | 'my-cart'
24
+ | 'my-payment'
25
+ | 'my-customer'
22
26
 
23
27
  export type Services = Partial<
24
28
  {