Skip to content

Commit 36f9e11

Browse files
committed
Post and put recipient
1 parent da54915 commit 36f9e11

File tree

7 files changed

+104
-6
lines changed

7 files changed

+104
-6
lines changed

packages/bygger-backend/src/routers/api/recipients/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@ const recipientsRouter = Router();
55

66
recipientsRouter.get('/', recipients.getAll);
77
recipientsRouter.get('/:recipientId', recipients.get);
8+
recipientsRouter.post('/', recipients.post);
9+
recipientsRouter.put('/:recipientId', recipients.put);
810

911
export default recipientsRouter;

packages/bygger-backend/src/routers/api/recipients/recipients.ts

+21
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,29 @@ const get: RequestHandler = async (req, res, next) => {
2020
}
2121
};
2222

23+
const post: RequestHandler = async (req, res, next) => {
24+
try {
25+
const recipient = await recipientService.post(req.body);
26+
res.json(recipient);
27+
} catch (error) {
28+
next(error);
29+
}
30+
};
31+
32+
const put: RequestHandler = async (req, res, next) => {
33+
const { recipientId } = req.params;
34+
try {
35+
const recipient = await recipientService.put(recipientId, req.body);
36+
res.json(recipient);
37+
} catch (error) {
38+
next(error);
39+
}
40+
};
41+
2342
const recipients = {
2443
getAll,
2544
get,
45+
post,
46+
put,
2647
};
2748
export default recipients;

packages/bygger-backend/src/services/RecipientService.ts

+18
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,22 @@ export class RecipientService {
2323
});
2424
return response.data as Recipient;
2525
}
26+
27+
async post(recipient: Recipient): Promise<Recipient> {
28+
const response = await fetchWithErrorHandling(`${this.formsApiUrl}${this.recipientsUrl}`, {
29+
method: 'POST',
30+
headers: { 'Content-Type': 'application/json' },
31+
body: JSON.stringify(recipient),
32+
});
33+
return response.data as Recipient;
34+
}
35+
36+
async put(recipientId: string, recipient: Recipient): Promise<Recipient> {
37+
const response = await fetchWithErrorHandling(`${this.formsApiUrl}${this.recipientsUrl}/${recipientId}`, {
38+
method: 'PUT',
39+
headers: { 'Content-Type': 'application/json' },
40+
body: JSON.stringify(recipient),
41+
});
42+
return response.data as Recipient;
43+
}
2644
}

packages/bygger/src/context/recipients/RecipientsContext.tsx

+28
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ interface RecipientsContextValues {
77
recipients: Recipient[];
88
newRecipient?: Partial<Recipient>;
99
addNewRecipient: () => void;
10+
saveRecipient: (recipient: Recipient) => Promise<Recipient | undefined>;
1011
}
1112

1213
const defaultContextValue = {
1314
isReady: false,
1415
recipients: [],
1516
addNewRecipient: () => {},
17+
saveRecipient: (_recipient) => Promise.reject(),
1618
};
1719

1820
interface RecipientState {
@@ -38,6 +40,31 @@ const RecipientsProvider = ({ children }: { children: ReactNode }) => {
3840
}
3941
}, [recipientState.isReady, loadRecipients]);
4042

43+
const saveRecipient = async (changedRecipient: Recipient) => {
44+
if (changedRecipient.recipientId === 'new') {
45+
const { recipientId, ...newRecipient } = changedRecipient;
46+
const recipient = await recipientsApi.post(newRecipient);
47+
console.log('Result', recipient);
48+
if (recipient) {
49+
setRecipientState((state) => ({ ...state, recipients: [...state.recipients, recipient], new: undefined }));
50+
}
51+
return recipient;
52+
}
53+
54+
const recipient = await recipientsApi.put(changedRecipient);
55+
if (recipient) {
56+
setRecipientState((state) => {
57+
const indexOfExisting = state.recipients.findIndex(
58+
(existing) => existing.recipientId === recipient.recipientId,
59+
);
60+
const newRecipients = [...state.recipients];
61+
newRecipients[indexOfExisting] = recipient;
62+
return { ...state, recipients: newRecipients };
63+
});
64+
}
65+
return recipient;
66+
};
67+
4168
const addNewRecipient = () => {
4269
if (recipientState.new === undefined) {
4370
setRecipientState((state) => ({ ...state, new: { recipientId: 'new' } }));
@@ -49,6 +76,7 @@ const RecipientsProvider = ({ children }: { children: ReactNode }) => {
4976
recipients: recipientState.recipients,
5077
newRecipient: recipientState.new,
5178
addNewRecipient,
79+
saveRecipient,
5280
};
5381
return <RecipientsContext.Provider value={value}>{children}</RecipientsContext.Provider>;
5482
};

packages/bygger/src/hooks/useFormsApi.ts

+21
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,29 @@ const useFormsApi = () => {
1616
}
1717
};
1818

19+
const postRecipient = async (recipient: Recipient): Promise<Recipient | undefined> => {
20+
try {
21+
return await http.post<Recipient>('/api/recipients', recipient);
22+
} catch (error) {
23+
const message = (error as Error)?.message;
24+
feedbackEmit.error(`Feil ved oppretting av ny mottaker. ${message}`);
25+
}
26+
};
27+
28+
const putRecipient = async (recipient: Recipient): Promise<Recipient | undefined> => {
29+
const { recipientId, ...updatedRecipient } = recipient;
30+
try {
31+
return await http.put<Recipient>(`/api/recipients/${recipientId}`, updatedRecipient);
32+
} catch (error) {
33+
const message = (error as Error)?.message;
34+
feedbackEmit.error(`Feil ved oppdatering av mottaker. ${message}`);
35+
}
36+
};
37+
1938
const recipientsApi = {
2039
getAll: getAllRecipients,
40+
post: postRecipient,
41+
put: putRecipient,
2142
};
2243

2344
return {

packages/bygger/src/recipients/RecipientButtonRow.tsx

Whitespace-only changes.

packages/bygger/src/recipients/RecipientRow.tsx

+14-6
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Button, HStack, Table, TextField } from '@navikt/ds-react';
33
import { makeStyles } from '@navikt/skjemadigitalisering-shared-components';
44
import { Recipient } from '@navikt/skjemadigitalisering-shared-domain';
55
import { useState } from 'react';
6+
import { useRecipients } from '../context/recipients/RecipientsContext';
67

78
const useStyles = makeStyles({
89
editRow: {
@@ -22,8 +23,10 @@ const useStyles = makeStyles({
2223
type ViewState = 'display' | 'editing';
2324

2425
const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
26+
const { saveRecipient } = useRecipients();
2527
const { recipientId } = recipient;
2628
const [viewState, setViewState] = useState<ViewState>(recipientId === 'new' ? 'editing' : 'display');
29+
const [isSaving, setIsSaving] = useState<boolean>(false);
2730
const [value, setValue] = useState(recipient);
2831
const styles = useStyles();
2932

@@ -69,7 +72,7 @@ const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
6972
label="Enhetsnavn"
7073
hideLabel
7174
size="small"
72-
value={value.name}
75+
defaultValue={value.name}
7376
onChange={(event) => updateValueProperty('name', event.currentTarget.value)}
7477
/>
7578
</Table.DataCell>
@@ -78,7 +81,7 @@ const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
7881
label="Postboksadresse"
7982
hideLabel
8083
size="small"
81-
value={value.poBoxAddress}
84+
defaultValue={value.poBoxAddress}
8285
onChange={(event) => updateValueProperty('poBoxAddress', event.currentTarget.value)}
8386
/>
8487
</Table.DataCell>
@@ -87,7 +90,7 @@ const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
8790
label="Postnr."
8891
hideLabel
8992
size="small"
90-
value={value.postalCode}
93+
defaultValue={value.postalCode}
9194
onChange={(event) => updateValueProperty('postalCode', event.currentTarget.value)}
9295
/>
9396
</Table.DataCell>
@@ -96,7 +99,7 @@ const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
9699
label="Poststed"
97100
hideLabel
98101
size="small"
99-
value={value.postalName}
102+
defaultValue={value.postalName}
100103
onChange={(event) => updateValueProperty('postalName', event.currentTarget.value)}
101104
/>
102105
</Table.DataCell>
@@ -106,9 +109,14 @@ const RecipientRow = ({ recipient }: { recipient: Partial<Recipient> }) => {
106109
<HStack gap="4" justify="end">
107110
<Button
108111
size="small"
109-
onClick={() => {
112+
loading={isSaving}
113+
onClick={async () => {
110114
console.log(value);
111-
setViewState('display');
115+
setIsSaving(true);
116+
// FIXME
117+
const result = await saveRecipient(value as Recipient);
118+
setIsSaving(false);
119+
if (result) setViewState('display');
112120
}}
113121
>
114122
Lagre

0 commit comments

Comments
 (0)