Skip to content

Commit 8286d87

Browse files
authored
Integrate save code route (#46)
- Add XSRF cookie utility
1 parent c960c9f commit 8286d87

File tree

2 files changed

+38
-10
lines changed

2 files changed

+38
-10
lines changed

src/app/apiFetch/Code.ts

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
/* tslint:disable:no-console*/
22
import { API_BASE_URL } from '../../config/config';
3+
import { getReqHeaders, HeadReqType, headResponseWrapper } from './utils';
34

45
export const saveCode = (code: string) => {
5-
return fetch(`${API_BASE_URL}code/save`, {
6-
body: JSON.stringify({
7-
code,
8-
}),
6+
return fetch(`${API_BASE_URL}code`, {
7+
body: code,
98
credentials: 'include',
10-
headers: {
11-
Accept: 'application/json',
12-
'Content-Type': 'application/json',
13-
},
14-
method: 'POST',
9+
headers: getReqHeaders(),
10+
method: 'PUT',
1511
})
1612
.then((response) => {
17-
return response.json();
13+
return headResponseWrapper(response, HeadReqType.OTHERS);
1814
})
1915
.then((data) => {
2016
return data;

src/app/apiFetch/utils/index.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export enum HeadReqType {
77
USERNAME = 'USERNAME',
88
PROFILE = 'PROFILE',
99
PASSWORD = 'PASSWORD',
10+
OTHERS = 'OTHERS',
1011
}
1112

1213
export function jsonResponseWrapper(response: any) {
@@ -54,10 +55,41 @@ export function headResponseWrapper(response: any, headReqType: HeadReqType) {
5455
: 'Please try again with correct password';
5556
type = resType.ERROR;
5657
break;
58+
case 500:
59+
case 403:
60+
error = headReqType === HeadReqType.OTHERS ? '' : '';
61+
type = resType.ERROR;
5762
}
5863
resolve({
5964
error,
6065
type,
6166
});
6267
});
6368
}
69+
70+
export function getReqHeaders() {
71+
const getCookie = (name: string) => {
72+
const cookies = Object.assign(
73+
{},
74+
...document.cookie.split('; ').map((cookie) => {
75+
const key = cookie.split('=')[0];
76+
const value = cookie.split('=')[1];
77+
78+
return { [key]: value };
79+
}),
80+
);
81+
return cookies[name];
82+
};
83+
const headersConfig = new Headers();
84+
headersConfig.append('Content-Type', 'application/json');
85+
headersConfig.append(SET_COOKIE.XSRF, getCookie(GET_COOKIE.XSRF));
86+
return headersConfig;
87+
}
88+
89+
export enum SET_COOKIE {
90+
XSRF = 'X-XSRF-TOKEN',
91+
}
92+
93+
export enum GET_COOKIE {
94+
XSRF = 'XSRF-TOKEN',
95+
}

0 commit comments

Comments
 (0)