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

feat: [M3-6816] - Add AGLB Create Route Drawer #9806

Merged
merged 11 commits into from
Oct 19, 2023
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/api-v4": Upcoming Features
---

Updated AGLB createLoadbalancerRoute endpoint with payload/schema ([#9806](https://github.com/linode/manager/pull/9806))
8 changes: 4 additions & 4 deletions packages/api-v4/src/aglb/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import Request, {
} from '../request';
import { Filter, Params, ResourcePage } from '../types';
import { BETA_API_ROOT } from '../constants';
import type { Route, RoutePayload, UpdateRoutePayload } from './types';
import { UpdateRouteSchema } from '@linode/validation';
import type { Route, CreateRoutePayload, UpdateRoutePayload } from './types';
import { UpdateRouteSchema, CreateRouteSchema } from '@linode/validation';

/**
* getLoadbalancerRoutes
Expand Down Expand Up @@ -51,13 +51,13 @@ export const getLoadbalancerRoute = (loadbalancerId: number, routeId: number) =>
*/
export const createLoadbalancerRoute = (
loadbalancerId: number,
data: RoutePayload
data: CreateRoutePayload
) =>
Request<Route>(
setURL(
`${BETA_API_ROOT}/aglb/${encodeURIComponent(loadbalancerId)}/routes`
),
setData(data),
setData(data, CreateRouteSchema),
setMethod('POST')
);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/manager": Upcoming Features
---

Add AGLB Create Route Drawer ([#9806](https://github.com/linode/manager/pull/9806))
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,90 @@ describe('Akamai Global Load Balancer routes page', () => {
cy.findByText('You reached a rate limit', { exact: false });
});
});

it('can create a Route', () => {
const loadbalancer = loadbalancerFactory.build();
const routes = routeFactory.buildList(1, { protocol: 'http' });

mockAppendFeatureFlags({
aglb: makeFeatureFlagData(true),
}).as('getFeatureFlags');
mockGetFeatureFlagClientstream().as('getClientStream');
mockGetLoadBalancer(loadbalancer).as('getLoadBalancer');
mockGetLoadBalancerRoutes(loadbalancer.id, routes).as('getRoutes');

cy.visitWithLogin(`/loadbalancers/${loadbalancer.id}/routes`);
cy.wait([
'@getFeatureFlags',
'@getClientStream',
'@getLoadBalancer',
'@getRoutes',
]);

ui.button
.findByTitle('Create Route')
.should('be.visible')
.should('be.enabled')
.click();

mockUpdateRoute(loadbalancer, routes[0]).as('updateRoute');

ui.drawer
.findByTitle('Create Route')
.should('be.visible')
.within(() => {
cy.findByLabelText('Route Label')
.should('be.visible')
.click()
.type(routes[0].label);

cy.get('[data-qa-radio="HTTP"]').find('input').should('be.checked');

ui.buttonGroup
.findButtonByTitle('Create Route')
.should('be.visible')
.should('be.enabled')
.click();
});
});

it('surfaces API errors in the Create Route Drawer', () => {
const loadbalancer = loadbalancerFactory.build();
const routes = routeFactory.buildList(1, { protocol: 'http' });

mockAppendFeatureFlags({
aglb: makeFeatureFlagData(true),
}).as('getFeatureFlags');
mockGetFeatureFlagClientstream().as('getClientStream');
mockGetLoadBalancer(loadbalancer).as('getLoadBalancer');
mockGetLoadBalancerRoutes(loadbalancer.id, routes).as('getRoutes');

cy.visitWithLogin(`/loadbalancers/${loadbalancer.id}/routes`);
cy.wait([
'@getFeatureFlags',
'@getClientStream',
'@getLoadBalancer',
'@getRoutes',
]);

ui.button
.findByTitle('Create Route')
.should('be.visible')
.should('be.enabled')
.click();

mockUpdateRoute(loadbalancer, routes[0]).as('updateRoute');

ui.drawer
.findByTitle('Create Route')
.should('be.visible')
.within(() => {
ui.buttonGroup
.findButtonByTitle('Create Route')
.should('be.visible')
.should('be.enabled')
.click();
});

cy.findByText('Label is required.', { exact: false });
});
28 changes: 23 additions & 5 deletions packages/manager/cypress/support/intercepts/load-balancers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { paginateResponse } from 'support/util/paginate';
import { makeErrorResponse } from 'support/util/errors';
import { apiMatcher } from 'support/util/intercepts';
import { paginateResponse } from 'support/util/paginate';
import { makeResponse } from 'support/util/response';

import type {
ServiceTarget,
Loadbalancer,
Configuration,
Certificate,
Configuration,
Loadbalancer,
Route,
ServiceTarget,
} from '@linode/api-v4';
import { makeResponse } from 'support/util/response';

/**
* Intercepts GET request to fetch an AGLB load balancer and mocks response.
Expand Down Expand Up @@ -103,6 +104,7 @@ export const mockUploadLoadBalancerCertificate = (
*
* @returns Cypress chainable.
*/
// TODO: AGLB - We should probably remove this mock and use "mockGetLoadBalancerServiceTargets" below.
export const mockGetServiceTargets = (
loadBalancer: Loadbalancer,
serviceTargets: ServiceTarget[]
Expand Down Expand Up @@ -149,6 +151,22 @@ export const mockCreateServiceTarget = (
);
};

/**
* Intercepts POST request to create a route and mocks response.
*
* @param loadBalancer - Load balancer for mocked route.
* @param route - Route with which to mock response.
*
* @returns Cypress chainable.
*/
export const mockCreateRoute = (loadBalancer: Loadbalancer, route: Route) => {
return cy.intercept(
'POST',
apiMatcher(`/aglb/${loadBalancer.id}/routes`),
makeResponse(route)
);
};

/**
* Intercepts GET requests to retrieve AGLB load balancer routes and mocks response.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { useOrder } from 'src/hooks/useOrder';
import { usePagination } from 'src/hooks/usePagination';
import { useLoadBalancerRoutesQuery } from 'src/queries/aglb/routes';

import { CreateRouteDrawer } from './Routes/CreateRouteDrawer';
import { DeleteRouteDialog } from './Routes/DeleteRouteDialog';
import { RuleDrawer } from './Routes/RuleDrawer';
import { RulesTable } from './RulesTable';
Expand All @@ -34,7 +35,7 @@ const PREFERENCE_KEY = 'loadbalancer-routes';

export const LoadBalancerRoutes = () => {
const { loadbalancerId } = useParams<{ loadbalancerId: string }>();

const [isCreateDrawerOpen, setIsCreateDrawerOpen] = useState(false);
const [isAddRuleDrawerOpen, setIsAddRuleDrawerOpen] = useState(false);
const [query, setQuery] = useState<string>();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
Expand Down Expand Up @@ -213,7 +214,12 @@ export const LoadBalancerRoutes = () => {
{/**
* TODO: AGLB: The Create Route behavior should be implemented in future AGLB tickets.
*/}
<Button buttonType="primary">Create Route</Button>
<Button
buttonType="primary"
onClick={() => setIsCreateDrawerOpen(true)}
>
Create Route
</Button>
</Stack>
<CollapsibleTable
TableItems={getTableItems()}
Expand All @@ -237,6 +243,11 @@ export const LoadBalancerRoutes = () => {
route={selectedRoute}
ruleIndexToEdit={selectedRuleIndex}
/>
<CreateRouteDrawer
loadbalancerId={Number(loadbalancerId)}
onClose={() => setIsCreateDrawerOpen(false)}
open={isCreateDrawerOpen}
/>
<DeleteRouteDialog
loadbalancerId={Number(loadbalancerId)}
onClose={() => setIsDeleteDialogOpen(false)}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { CreateRoutePayload } from '@linode/api-v4';
import { useFormik } from 'formik';
import React from 'react';

import { ActionsPanel } from 'src/components/ActionsPanel/ActionsPanel';
import { Drawer } from 'src/components/Drawer';
import { FormControlLabel } from 'src/components/FormControlLabel';
import { FormHelperText } from 'src/components/FormHelperText';
import { FormLabel } from 'src/components/FormLabel';
import { Notice } from 'src/components/Notice/Notice';
import { Radio } from 'src/components/Radio/Radio';
import { RadioGroup } from 'src/components/RadioGroup';
import { TextField } from 'src/components/TextField';
import { useLoadBalancerRouteCreateMutation } from 'src/queries/aglb/routes';
import { capitalize } from 'src/utilities/capitalize';
import { getFormikErrorsFromAPIErrors } from 'src/utilities/formikErrorUtils';
import { scrollErrorIntoView } from 'src/utilities/scrollErrorIntoView';

interface Props {
loadbalancerId: number;
onClose: () => void;
open: boolean;
}

const initialValues: CreateRoutePayload = {
label: '',
protocol: 'http',
rules: [],
};

export const CreateRouteDrawer = (props: Props) => {
const { loadbalancerId, onClose: _onClose, open } = props;

const {
error,
mutateAsync: createRoute,
reset,
} = useLoadBalancerRouteCreateMutation(loadbalancerId);

const formik = useFormik<CreateRoutePayload>({
initialValues,
async onSubmit(values) {
try {
await createRoute(values);
onClose();
} catch (errors) {
scrollErrorIntoView();
formik.setErrors(getFormikErrorsFromAPIErrors(errors));
}
},
});

const onClose = () => {
formik.resetForm();
reset();
_onClose();
};

const generalError = error?.find((e) => !e.field)?.reason;

return (
<Drawer onClose={onClose} open={open} title="Create Route">
<form onSubmit={formik.handleSubmit}>
{generalError && <Notice text={generalError} variant="error" />}
<TextField
errorText={formik.touched.label ? formik.errors.label : undefined}
label="Route Label"
name="label"
onChange={formik.handleChange}
value={formik.values.label}
/>
<RadioGroup
onChange={(_, value) => formik.setFieldValue('protocol', value)}
value={formik.values.protocol}
>
<FormLabel sx={(theme) => ({ marginTop: theme.spacing(1) })}>
Protocol
</FormLabel>
<FormControlLabel
control={<Radio />}
data-qa-radio={'HTTP'}
label="HTTP"
value="http"
/>
<FormControlLabel
control={<Radio />}
data-qa-radio={'TCP'}
label="TCP"
value="tcp"
/>
<FormHelperText error>
{formik.touched.protocol
? typeof formik.errors.protocol === 'string'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to narrow this type because it returned string | undefined and capitalize doesn't like that.

? capitalize(formik.errors.protocol)
: undefined
: undefined}
</FormHelperText>
</RadioGroup>
<ActionsPanel
primaryButtonProps={{
label: 'Create Route',
loading: formik.isSubmitting,
type: 'submit',
}}
secondaryButtonProps={{
label: 'Cancel',
onClick: onClose,
}}
/>
</form>
</Drawer>
);
};
19 changes: 19 additions & 0 deletions packages/manager/src/queries/aglb/routes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
CreateRoutePayload,
createLoadbalancerRoute,
deleteLoadbalancerRoute,
getLoadbalancerRoutes,
updateLoadbalancerRoute,
Expand Down Expand Up @@ -29,6 +31,23 @@ export const useLoadBalancerRoutesQuery = (
);
};

export const useLoadBalancerRouteCreateMutation = (loadbalancerId: number) => {
const queryClient = useQueryClient();
return useMutation<Route, APIError[], CreateRoutePayload>(
(data) => createLoadbalancerRoute(loadbalancerId, data),
{
onSuccess() {
queryClient.invalidateQueries([
QUERY_KEY,
'loadbalancer',
loadbalancerId,
'routes',
]);
},
}
);
};

export const useLoadBalancerRouteUpdateMutation = (
loadbalancerId: number,
routeId: number
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/validation": Upcoming Features
---

Added AGLB CreateRouteSchema ([#9806](https://github.com/linode/manager/pull/9806))
5 changes: 5 additions & 0 deletions packages/validation/src/loadbalancers.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ export const CreateServiceTargetSchema = object({
healthcheck: HealthCheckSchema,
});

export const CreateRouteSchema = object({
jaalah-akamai marked this conversation as resolved.
Show resolved Hide resolved
label: string().required('Label is required.'),
protocol: string().oneOf(['http', 'tcp']),
});

const RouteServiceTargetSchema = object({
id: number()
.min(0, 'Service Target ID is required.')
Expand Down