Skip to content

Commit

Permalink
fix: updated code and tested it
Browse files Browse the repository at this point in the history
  • Loading branch information
phofmann committed Nov 6, 2024
1 parent 6431e45 commit a5c328f
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,34 @@ import { UpdateAction } from '@commercetools/sdk-client-v2';

import { createApiRoot } from '../client/create.client';
import CustomError from '../errors/custom.error';
import { Resource } from '../interfaces/resource.interface';
import { ControllerResult } from '../types/controller.types';
import { logger } from '../utils/logger.utils';
import { Cart } from '@commercetools/platform-sdk';
import { ExtensionAction } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/extension';

/**
* Handle the create action
*
* @param {Resource} resource The resource from the request body
* @returns {object}
*/
const create = async (resource: Resource) => {
let productId = undefined;

const create = async (cart: Cart): Promise<ControllerResult> => {
try {
logger.info(`Running API Extension for Cart Create (ID: ${cart.id})`);
const updateActions: Array<UpdateAction> = [];

// Deserialize the resource to a CartDraft
const cartDraft = JSON.parse(JSON.stringify(resource));

if (cartDraft.obj.lineItems.length !== 0) {
productId = cartDraft.obj.lineItems[0].productId;
}

// Fetch the product with the ID
if (productId) {
await createApiRoot()
.products()
.withId({ ID: productId })
.get()
.execute();
// This is demo code.
// You can do something e.g. with each lineitem
// If you need the whole product, load it first...
if (cart.lineItems.length !== 0) {
const productId = cart.lineItems[0].productId;
// Fetch the product with the ID
if (productId) {
await createApiRoot()
.products()
.withId({ ID: productId })
.get()
.execute();

// Work with the product
// Work with the product
}
}

// Create the UpdateActions Object to return it to the client
Expand All @@ -42,10 +40,13 @@ const create = async (resource: Resource) => {

updateActions.push(updateAction);

// API Extensions will perform the update actions that you return. You don't have to do this yourself.
// https://docs.commercetools.com/api/projects/api-extensions#updates-requested
return { statusCode: 200, actions: updateActions };
} catch (error) {
// Retry or handle the error
// Create an error object
logger.error(`Internal server error on CartController: ${error}`);
if (error instanceof Error) {
throw new CustomError(
400,
Expand All @@ -55,26 +56,29 @@ const create = async (resource: Resource) => {
}
};

// Controller for update actions
// const update = (resource: Resource) => {};
/**
* Handle the update action
*/
const update = (cart: Cart): ControllerResult => {
logger.info(`Running API Extension for Cart Update (ID: ${cart.id})`);
return;
};

/**
* Handle the cart controller according to the action
*
* @param {string} action The action that comes with the request. Could be `Create` or `Update`
* @param {Resource} resource The resource from the request body
* @returns {Promise<object>} The data from the method that handles the action
*/
export const cartController = async (action: string, resource: Resource) => {
export const cartController = async (
action: ExtensionAction,
resource: Cart
) => {
switch (action) {
case 'Create': {
const data = create(resource);
return data;
}
case 'Create':
return create(resource);
case 'Update':
break;
return update(resource);

default:
logger.error(` Action ('${action}') not recognized.`);
throw new CustomError(
500,
`Internal Server Error - Resource not recognized. Allowed values are 'Create' or 'Update'.`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@ import { Request, Response } from 'express';
import { apiSuccess } from '../api/success.api';
import CustomError from '../errors/custom.error';
import { cartController } from './cart.controller';
import { logger } from '../utils/logger.utils';
import { ParamsDictionary } from 'express-serve-static-core';
import { BusinessUnitReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/business-unit';
import { CartReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/cart';
import { CustomerGroupReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/customer-group';
import { CustomerReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/customer';
import { OrderReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/order';
import { PaymentReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/payment';
import { QuoteReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/quote';
import { QuoteRequestReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/quote-request';
import { ShoppingListReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/shopping-list';
import { StagedQuoteReference } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/staged-quote';
import { ExtensionAction } from '@commercetools/platform-sdk/dist/declarations/src/generated/models/extension';
import { ControllerResult } from '../types/controller.types';
import { paymentController } from './payment.controller';
import { orderController } from './order.controller';

/**
* Exposed service endpoint.
Expand All @@ -12,47 +28,73 @@ import { cartController } from './cart.controller';
* @param {Response} response The express response
* @returns
*/
export const post = async (request: Request, response: Response) => {
// Deserialize the action and resource from the body
export const post = async (
request: Request<
ParamsDictionary,
any,
{
action: ExtensionAction;
resource?:
| BusinessUnitReference
| CartReference
| CustomerGroupReference
| CustomerReference
| OrderReference
| PaymentReference
| QuoteReference
| QuoteRequestReference
| ShoppingListReference
| StagedQuoteReference;
}
>,
response: Response
) => {
// Check request body
if (!request.body) {
logger.error('Missing request body.');
throw new CustomError(400, 'Bad request: No Pub/Sub message was received');
}

// Get the action and resource from the body
const { action, resource } = request.body;

if (!action || !resource) {
throw new CustomError(400, 'Bad request - Missing body parameters.');
if (!action) {
logger.error('Missing action in body.');
throw new CustomError(400, 'Bad request - Missing action parameter.');
}
if (!resource) {
logger.error('Missing resource in body.');
throw new CustomError(400, 'Bad request - Missing resource parameter.');
}
if (!resource.obj) {
logger.error('Missing obj in resource.');
throw new CustomError(400, 'Bad request - Missing obj in resource.');
}

// Identify the type of resource in order to redirect
// to the correct controller
// to the correct controller;
let data: ControllerResult = undefined;
switch (resource.typeId) {
case 'cart':
try {
const data = await cartController(action, resource);

if (data && data.statusCode === 200) {
apiSuccess(200, data.actions, response);
return;
}

throw new CustomError(
data ? data.statusCode : 400,
JSON.stringify(data)
);
} catch (error) {
if (error instanceof Error) {
throw new CustomError(500, error.message);
}
}

case 'cart': {
data = await cartController(action, resource.obj);
break;
}
case 'payment':
data = paymentController(action, resource.obj);
break;

case 'order':
data = orderController(action, resource.obj);
break;

default:
logger.error(
" Resource not recognized. Allowed values are 'cart', 'payment' or 'order'."
);
throw new CustomError(
500,
`Internal Server Error - Resource not recognized. Allowed values are 'cart', 'payments' or 'orders'.`
);
}
apiSuccess(data?.statusCode || 200, data?.actions || [], response);
};

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { UpdateAction } from '@commercetools/sdk-client-v2';

export type ControllerResult =
| { statusCode: number; actions: Array<UpdateAction> }
| undefined;

0 comments on commit a5c328f

Please sign in to comment.