move all fetch requets from components to actions/fetch

This commit is contained in:
HF 2021-03-17 02:24:30 +01:00
parent 1c0b1101b0
commit 2b9cae2ca2
11 changed files with 210 additions and 264 deletions

View File

@ -1,11 +1,11 @@
/* /*
* Collect api fetch commands for actions here * Collect api fetch commands for actions here
* (chunk and tiles requests in ui/ChunkLoader*.js) * (chunk and tiles requests in ui/ChunkLoader*.js)
* (user settings requests in their components)
* *
* @flow * @flow
*/ */
import { t } from 'ttag';
/* /*
* Adds customizeable timeout to fetch * Adds customizeable timeout to fetch
@ -27,123 +27,213 @@ async function fetchWithTimeout(resource, options) {
} }
/* /*
* block / unblock user * Parse response from API
* userId id of user to block * @param response
* block true if block, false if unblock * @return Object of response
* return error string or null if successful
*/ */
export async function requestBlock(userId: number, block: boolean) { async function parseAPIresponse(response) {
const response = await fetchWithTimeout('api/block', { if (!response.ok) {
method: 'POST', const code = response.status;
credentials: 'include', return {
headers: { errors: [t`Connection error ${code} :(`],
'Content-Type': 'application/json', };
}, }
body: JSON.stringify({
userId,
block,
}),
});
try { try {
const res = await response.json(); return await response.json();
if (res.errors) { } catch (e) {
return res.errors[0]; return {
} errors: [t`Server answered with gibberish :(`],
if (response.ok && res.status === 'ok') { };
return null;
}
return 'Unknown Error';
} catch {
return 'Connection Error';
} }
} }
/*
* Make API POST Request
* @param url URL of post api endpoint
* @param body Body of request
* @return Object with response or error Array
*/
async function makeAPIPOSTRequest(url, body) {
try {
const response = await fetchWithTimeout(url, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return parseAPIresponse(response);
} catch (e) {
return {
errors: [t`Could not connect to server, please try again later :(`],
};
}
}
/*
* Make API GET Request
* @param url URL of get api endpoint
* @return Object with response or error Array
*/
async function makeAPIGETRequest(url) {
try {
const response = await fetchWithTimeout(url, {
credentials: 'include',
});
return parseAPIresponse(response);
} catch (e) {
return {
errors: [t`Could not connect to server, please try again later :(`],
};
}
}
/*
* block / unblock user
* @param userId id of user to block
* @param block true if block, false if unblock
* @return error string or null if successful
*/
export async function requestBlock(userId: number, block: boolean) {
const res = await makeAPIPOSTRequest(
'api/block',
{ userId, block },
);
if (res.errors) {
return res.errors[0];
}
if (res.status === 'ok') {
return null;
}
return t`Unknown Error`;
}
/* /*
* start new DM channel with user * start new DM channel with user
* query Object with either userId: number or userName: string * @param query Object with either userId: number or userName: string
* return channel Array on success, error string if not * @return channel Array on success, error string if not
*/ */
export async function requestStartDm(query) { export async function requestStartDm(query) {
const response = await fetchWithTimeout('api/startdm', { const res = await makeAPIPOSTRequest(
method: 'POST', 'api/startdm',
credentials: 'include', query,
headers: { );
'Content-Type': 'application/json', if (res.errors) {
}, return res.errors[0];
body: JSON.stringify(query),
});
try {
const res = await response.json();
if (res.errors) {
return res.errors[0];
}
if (response.ok && res.channel) {
const { channel } = res;
return channel;
}
return 'Unknown Error';
} catch {
return 'Connection Error';
} }
if (res.channel) {
return res.channel;
}
return t`Unknown Error`;
} }
/* /*
* set receiving of all DMs on/off * set receiving of all DMs on/off
* block true if blocking all dms, false if unblocking * @param block true if blocking all dms, false if unblocking
* return error string or null if successful * @return error string or null if successful
*/ */
export async function requestBlockDm(block: boolean) { export async function requestBlockDm(block: boolean) {
const response = await fetchWithTimeout('api/blockdm', { const res = await makeAPIPOSTRequest(
method: 'POST', 'api/blockdm',
credentials: 'include', { block },
headers: { );
'Content-Type': 'application/json', if (res.errors) {
}, return res.errors[0];
body: JSON.stringify({ block }),
});
try {
const res = await response.json();
if (res.errors) {
return res.errors[0];
}
if (response.ok && res.status === 'ok') {
return null;
}
return 'Unknown Error';
} catch {
return 'Connection Error';
} }
if (res.status === 'ok') {
return null;
}
return t`Unknown Error`;
} }
/* /*
* leaving Chat Channel (i.e. DM channel) * leaving Chat Channel (i.e. DM channel)
* channelId 8nteger id of channel * @param channelId 8nteger id of channel
* return error string or null if successful * @return error string or null if successful
*/ */
export async function requestLeaveChan(channelId: boolean) { export async function requestLeaveChan(channelId: boolean) {
const response = await fetchWithTimeout('api/leavechan', { const res = await makeAPIPOSTRequest(
method: 'POST', 'api/leavechan',
credentials: 'include', { channelId },
headers: { );
'Content-Type': 'application/json', if (res.errors) {
}, return res.errors[0];
body: JSON.stringify({ channelId }),
});
try {
const res = await response.json();
if (res.errors) {
return res.errors[0];
}
if (response.ok && res.status === 'ok') {
return null;
}
return 'Unknown Error';
} catch {
return 'Connection Error';
} }
if (res.status === 'ok') {
return null;
}
return t`Unknown Error`;
}
export function requestSolveCaptcha(text) {
return makeAPIPOSTRequest(
'api/captcha',
{ text },
);
}
export function requestPasswordChange(newPassword, password) {
return makeAPIPOSTRequest(
'api/auth/change_passwd',
{ password, newPassword },
);
}
export async function requestResendVerify() {
return makeAPIGETRequest(
'./api/auth/resend_verify',
);
}
export function requestMcLink(accepted) {
return makeAPIPOSTRequest(
'api/auth/mclink',
{ accepted },
);
}
export function requestNameChange(name) {
return makeAPIPOSTRequest(
'api/auth/change_name',
{ name },
);
}
export function requestMailChange(email, password) {
return makeAPIPOSTRequest(
'api/auth/change_mail',
{ email, password },
);
}
export function requestLogin(nameoremail, password) {
return makeAPIPOSTRequest(
'api/auth/local',
{ nameoremail, password },
);
}
export function requestRegistration(name, email, password) {
return makeAPIPOSTRequest(
'api/auth/register',
{ name, email, password },
);
}
export function requestNewPassword(email) {
return makeAPIPOSTRequest(
'api/auth/restore_password',
{ email },
);
}
export function requestDeleteAccount(password) {
return makeAPIPOSTRequest(
'api/auth/delete_account',
{ password },
);
} }

View File

@ -6,8 +6,9 @@
import React from 'react'; import React from 'react';
import { t } from 'ttag'; import { t } from 'ttag';
import { import {
validateEMail, validatePassword, parseAPIresponse, validateEMail, validatePassword,
} from '../utils/validation'; } from '../utils/validation';
import { requestMailChange } from '../actions/fetch';
function validate(email, password) { function validate(email, password) {
const errors = []; const errors = [];
@ -20,23 +21,6 @@ function validate(email, password) {
return errors; return errors;
} }
async function submitMailchange(email, password) {
const body = JSON.stringify({
email,
password,
});
const response = await fetch('./api/auth/change_mail', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body,
credentials: 'include',
});
return parseAPIresponse(response);
}
class ChangeMail extends React.Component { class ChangeMail extends React.Component {
constructor() { constructor() {
super(); super();
@ -64,7 +48,7 @@ class ChangeMail extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors } = await submitMailchange(email, password); const { errors: resperrors } = await requestMailChange(email, password);
if (resperrors) { if (resperrors) {
this.setState({ this.setState({
errors: resperrors, errors: resperrors,

View File

@ -5,7 +5,8 @@
import React from 'react'; import React from 'react';
import { t } from 'ttag'; import { t } from 'ttag';
import { validateName, parseAPIresponse } from '../utils/validation'; import { validateName } from '../utils/validation';
import { requestNameChange } from '../actions/fetch';
function validate(name) { function validate(name) {
@ -17,22 +18,6 @@ function validate(name) {
return errors; return errors;
} }
async function submitNamechange(name) {
const body = JSON.stringify({
name,
});
const response = await fetch('./api/auth/change_name', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body,
credentials: 'include',
});
return parseAPIresponse(response);
}
class ChangeName extends React.Component { class ChangeName extends React.Component {
constructor() { constructor() {
super(); super();
@ -58,7 +43,7 @@ class ChangeName extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors } = await submitNamechange(name); const { errors: resperrors } = await requestNameChange(name);
if (resperrors) { if (resperrors) {
this.setState({ this.setState({
errors: resperrors, errors: resperrors,

View File

@ -5,7 +5,8 @@
import React from 'react'; import React from 'react';
import { t } from 'ttag'; import { t } from 'ttag';
import { validatePassword, parseAPIresponse } from '../utils/validation'; import { validatePassword } from '../utils/validation';
import { requestPasswordChange } from '../actions/fetch';
function validate(mailreg, password, newPassword, confirmPassword) { function validate(mailreg, password, newPassword, confirmPassword) {
const errors = []; const errors = [];
@ -24,24 +25,6 @@ function validate(mailreg, password, newPassword, confirmPassword) {
return errors; return errors;
} }
async function submitPasswordChange(newPassword, password) {
const body = JSON.stringify({
password,
newPassword,
});
const response = await fetch('./api/auth/change_passwd', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body,
credentials: 'include',
});
return parseAPIresponse(response);
}
class ChangePassword extends React.Component { class ChangePassword extends React.Component {
constructor() { constructor() {
super(); super();
@ -78,7 +61,7 @@ class ChangePassword extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors } = await submitPasswordChange( const { errors: resperrors } = await requestPasswordChange(
newPassword, newPassword,
password, password,
); );

View File

@ -7,7 +7,8 @@ import React from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { t } from 'ttag'; import { t } from 'ttag';
import { validatePassword, parseAPIresponse } from '../utils/validation'; import { validatePassword } from '../utils/validation';
import { requestDeleteAccount } from '../actions/fetch';
import { logoutUser } from '../actions'; import { logoutUser } from '../actions';
function validate(password) { function validate(password) {
@ -19,22 +20,6 @@ function validate(password) {
return errors; return errors;
} }
async function submitDeleteAccount(password) {
const body = JSON.stringify({
password,
});
const response = await fetch('./api/auth/delete_account', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body,
credentials: 'include',
});
return parseAPIresponse(response);
}
class DeleteAccount extends React.Component { class DeleteAccount extends React.Component {
constructor() { constructor() {
super(); super();
@ -60,7 +45,7 @@ class DeleteAccount extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors } = await submitDeleteAccount(password); const { errors: resperrors } = await requestDeleteAccount(password);
if (resperrors) { if (resperrors) {
this.setState({ this.setState({
errors: resperrors, errors: resperrors,

View File

@ -31,11 +31,6 @@ const HelpModal = () => {
const bindShift = <kbd> {c('keybinds').t`Shift`}</kbd>; const bindShift = <kbd> {c('keybinds').t`Shift`}</kbd>;
const bindC = <kbd>{c('keybinds').t`C`}</kbd>; const bindC = <kbd>{c('keybinds').t`C`}</kbd>;
const hCaptchaPP = <a href="https://hcaptcha.com/privacy">{t`Privacy Policy`}</a>;
const reCaptchaPP = <a href="https://policies.google.com/privacy">{t`Privacy Policy`}</a>;
const hCaptchaTOS = <a href="https://hcaptcha.com/terms">{t`Terms of Service`}</a>;
const reCaptchaTOS = <a href="https://policies.google.com/terms">{t`Terms of Service`}</a>;
const guildedLink = <a href="https://pixelplanet.fun/guilded">guilded</a>; const guildedLink = <a href="https://pixelplanet.fun/guilded">guilded</a>;
const getIPLink = <a href="https://www.whatismyip.com/">{t`your IP`}</a>; const getIPLink = <a href="https://www.whatismyip.com/">{t`your IP`}</a>;
const mailLink = <a href="mailto:pixelplanetdev@gmail.com">pixelplanetdev@gmail.com</a>; const mailLink = <a href="mailto:pixelplanetdev@gmail.com">pixelplanetdev@gmail.com</a>;

View File

@ -7,8 +7,9 @@ import { connect } from 'react-redux';
import { t } from 'ttag'; import { t } from 'ttag';
import { import {
validateEMail, validateName, validatePassword, parseAPIresponse, validateEMail, validateName, validatePassword,
} from '../utils/validation'; } from '../utils/validation';
import { requestLogin } from '../actions/fetch';
import { loginUser } from '../actions'; import { loginUser } from '../actions';
@ -24,22 +25,6 @@ function validate(nameoremail, password) {
return errors; return errors;
} }
async function submitLogin(nameoremail, password) {
const body = JSON.stringify({
nameoremail,
password,
});
const response = await fetch('./api/auth/local', {
method: 'POST',
body,
headers: {
'Content-Type': 'application/json',
},
});
return parseAPIresponse(response);
}
const inputStyles = { const inputStyles = {
display: 'inline-block', display: 'inline-block',
width: '100%', width: '100%',
@ -73,7 +58,7 @@ class LogInForm extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors, me } = await submitLogin( const { errors: resperrors, me } = await requestLogin(
nameoremail, nameoremail,
password, password,
); );

View File

@ -4,7 +4,8 @@
*/ */
import React from 'react'; import React from 'react';
import { t } from 'ttag'; import { t } from 'ttag';
import { validateEMail, parseAPIresponse } from '../utils/validation'; import { validateEMail } from '../utils/validation';
import { requestNewPassword } from '../actions/fetch';
function validate(email) { function validate(email) {
const errors = []; const errors = [];
@ -13,21 +14,6 @@ function validate(email) {
return errors; return errors;
} }
async function submitNewpass(email) {
const body = JSON.stringify({
email,
});
const response = await fetch('./api/auth/restore_password', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body,
});
return parseAPIresponse(response);
}
const inputStyles = { const inputStyles = {
display: 'inline-block', display: 'inline-block',
width: '100%', width: '100%',
@ -60,7 +46,7 @@ class NewPasswordForm extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors } = await submitNewpass(email); const { errors: resperrors } = await requestNewPassword(email);
if (resperrors) { if (resperrors) {
this.setState({ this.setState({
errors: resperrors, errors: resperrors,

View File

@ -7,8 +7,9 @@ import React from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { t } from 'ttag'; import { t } from 'ttag';
import { import {
validateEMail, validateName, validatePassword, parseAPIresponse, validateEMail, validateName, validatePassword,
} from '../utils/validation'; } from '../utils/validation';
import { requestRegistration } from '../actions/fetch';
import { showUserAreaModal, loginUser } from '../actions'; import { showUserAreaModal, loginUser } from '../actions';
@ -28,25 +29,6 @@ function validate(name, email, password, confirmPassword) {
return errors; return errors;
} }
async function submitRegistration(name, email, password) {
const body = JSON.stringify({
name,
email,
password,
});
const response = await fetch('./api/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body,
credentials: 'include',
});
return parseAPIresponse(response);
}
const inputStyles = { const inputStyles = {
display: 'inline-block', display: 'inline-block',
width: '100%', width: '100%',
@ -83,7 +65,7 @@ class SignUpForm extends React.Component {
if (errors.length > 0) return; if (errors.length > 0) return;
this.setState({ submitting: true }); this.setState({ submitting: true });
const { errors: resperrors, me } = await submitRegistration( const { errors: resperrors, me } = await requestRegistration(
name, name,
email, email,
password, password,

View File

@ -6,8 +6,8 @@ import React from 'react';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { t } from 'ttag'; import { t } from 'ttag';
import { parseAPIresponse } from '../utils/validation';
import { setMinecraftName, remFromMessages } from '../actions'; import { setMinecraftName, remFromMessages } from '../actions';
import { requestResendVerify, requestMcLink } from '../actions/fetch';
class UserMessages extends React.Component { class UserMessages extends React.Component {
@ -31,11 +31,8 @@ class UserMessages extends React.Component {
resentVerify: true, resentVerify: true,
}); });
const response = await fetch('./api/auth/resend_verify', { const { errors } = await requestResendVerify();
credentials: 'include',
});
const { errors } = await parseAPIresponse(response);
const verifyAnswer = (errors) const verifyAnswer = (errors)
? errors[0] ? errors[0]
: t`A new verification mail is getting sent to you.`; : t`A new verification mail is getting sent to you.`;
@ -50,15 +47,9 @@ class UserMessages extends React.Component {
this.setState({ this.setState({
sentLink: true, sentLink: true,
}); });
const body = JSON.stringify({ accepted });
const rep = await fetch('./api/auth/mclink', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
credentials: 'include',
});
const { errors } = parseAPIresponse(rep); const { errors } = await requestMcLink(accepted);
if (errors) { if (errors) {
this.setState({ this.setState({
linkAnswer: errors[0], linkAnswer: errors[0],

View File

@ -61,23 +61,3 @@ export function validatePassword(password) {
} }
return false; return false;
} }
/*
* makes sure that responses from the api
* includes errors when failure occures
*/
export async function parseAPIresponse(response) {
try {
const resp = await response.json();
if (!response.ok && !resp.errors) {
return {
errors: [t`Could not connect to server, please try again later :(`],
};
}
return resp;
} catch (e) {
return {
errors: [t`I think we experienced some error :(`],
};
}
}