Skip to content

Commit

Permalink
apply merge request changes technologiestiftung#554
Browse files Browse the repository at this point in the history
  • Loading branch information
joergreichert committed Apr 9, 2023
1 parent f9ec786 commit 13d11bb
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 72 deletions.
82 changes: 52 additions & 30 deletions src/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const handlers = [
return res(ctx.status(201));
}),

rest.delete(`${location}/delete`, (req, res, ctx) => {
rest.delete(`${location}/delete/:type`, (req, res, ctx) => {
// console.log('intercepting DELETE requests');
const json: Payload = {};
let body: Record<string, any> = {};
Expand All @@ -72,9 +72,18 @@ export const handlers = [
} else {
body = req.body ? req.body : {};
}
const queryType = body ? getProperty(body, 'queryType') : '';
const { type } = req.params;
if (!type) {
return res(ctx.status(400), ctx.json({ message: 'type is undefined' }));
}
if (typeof type !== 'string') {
return res(
ctx.status(400),
ctx.json({ message: 'type is not a string' })
);
}
// console.log(body);
switch (queryType) {
switch (type) {
case 'unadopt': {
// remove from adopted trees list
// adoptedTreeIds[]
Expand All @@ -86,7 +95,7 @@ export const handlers = [
}
case undefined:
case null: {
console.log(' queryType is undefined or null');
console.log(' type is undefined or null');
break;
}
default: {
Expand All @@ -95,17 +104,25 @@ export const handlers = [
}
return res(ctx.status(201), ctx.json(json));
}),
rest.post(`${location}/post`, (req, res, ctx) => {
rest.post(`${location}/post/:type`, (req, res, ctx) => {
let json: Payload = {};
let body: Record<string, any> = {};
if (typeof req.body === 'string') {
body = JSON.parse(req.body);
} else {
body = req.body ? req.body : {};
}
const queryType = body ? getProperty(body, 'queryType') : '';

switch (queryType) {
const { type } = req.params;
if (!type) {
return res(ctx.status(400), ctx.json({ message: 'type is undefined' }));
}
if (typeof type !== 'string') {
return res(
ctx.status(400),
ctx.json({ message: 'type is not a string' })
);
}
switch (type) {
case 'water': {
treesWatered.push({
tree_id: getProperty(body, 'tree_id'),
Expand All @@ -132,7 +149,7 @@ export const handlers = [
watered: '1',
});
}
json = { data: 'watered tree', message: `${queryType}` };
json = { data: 'watered tree', message: `${type}` };
break;
}
case 'adopt': {
Expand All @@ -156,12 +173,12 @@ export const handlers = [
watered: '0',
});
}
json = { data: 'tree was adopted', message: `${queryType}` };
json = { data: 'tree was adopted', message: `${type}` };
break;
}
case undefined:
case null: {
console.error('queryType is not defiend');
console.error('type url param is not defiend');
break;
}
default: {
Expand All @@ -177,17 +194,25 @@ export const handlers = [
return res(ctx.status(200), ctx.json({ foo: 'bar' }));
}),

rest.get(`${location}/get`, async (req, res, ctx) => {
rest.get(`${location}/get/:type`, async (req, res, ctx) => {
let json: Payload = {};

// const queries = getUrlQueries(req.url.href);
// const query = req.url.searchParams;
// const queryType = query.get('queryType');
const queryType = getProperty(req.url.searchParams, 'queryType');

switch (queryType) {
case 'treesWateredByUser': {
json = { data: treesWatered, message: `${queryType}` };
const { type } = req.params as Record<string, unknown>;
if (!type) {
return res(
ctx.status(400),
ctx.json({ message: 'url param is missing' })
);
}
if (typeof type === 'string') {
return res(
ctx.status(400),
ctx.json({ message: 'url param is not a string' })
);
}
switch (type) {
case 'treeswateredbyuser': {
json = { data: treesWatered, message: `${type}` };

break;
}
Expand All @@ -205,25 +230,25 @@ export const handlers = [
break;
}
case 'adopted': {
json = { data: [...adoptedTreeIds], message: `${queryType}` };
json = { data: [...adoptedTreeIds], message: `${type}` };
break;
}
case 'istreeadopted': {
const id = getProperty(req.url.searchParams, 'id');
json = {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
data: adoptedTreeIds.includes(id) ? true : false,
message: `${queryType}`,
message: `${type}`,
};
break;
}
case 'wateredbyuser': {
// const uuid = queries.get('uuid'); // if we need it
json = { data: treesWatered, message: `${queryType}` };
json = { data: treesWatered, message: `${type}` };
break;
}
case 'wateredandadopted': {
json = { data: wateredAndAdopted, message: `${queryType}` };
json = { data: wateredAndAdopted, message: `${type}` };
break;
}
case 'lastwatered': {
Expand All @@ -237,12 +262,12 @@ export const handlers = [
}
});
const lastWateredByUserFiltered = lastWateredByUser.filter(Boolean); // https://stackoverflow.com/a/281335/1770432
json = { data: lastWateredByUserFiltered, message: `${queryType}` };
json = { data: lastWateredByUserFiltered, message: `${type}` };
break;
}
case 'watered': {
const watered = treesWatered.map(tree => tree.tree_id);
json = { data: { watered }, message: `${queryType}` };
json = { data: { watered }, message: `${type}` };

break;
}
Expand All @@ -253,7 +278,7 @@ export const handlers = [
json = {
data: [],
url: req.url,
message: `case ${queryType} with url "${req.url}" in default case. Not yet defined and passed through`,
message: `case ${type} with url "${req.url}" in default case. Not yet defined and passed through`,
...originalResponse,
};
// console.log('response is patched and gets passed through', json);
Expand All @@ -267,9 +292,6 @@ export const handlers = [
rest.get(
'https://tsb-trees-api-user-management.now.sh/api/user',
(req, res, ctx) => {
// const query = req.url.searchParams;
// const queryType = query.get('queryType');
// console.log('queryType', queryType);

const userid = getProperty(req.url.searchParams, 'id');
const json: Payload = {
Expand Down
1 change: 1 addition & 0 deletions src/utils/requestUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export async function requests<
const msg = await response.text();
throw new Error(msg);
}
if (response.status === 204) return {} as ReturnType;
const json = await response.json();
return json;
} catch (err) {
Expand Down
6 changes: 3 additions & 3 deletions src/utils/requests/adoptTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ export const adoptTree = async ({
token: string;
userId: string;
}): Promise<Tree> => {
const url = createAPIUrl(`/post`);
const url = createAPIUrl(`/post/adopt`);

await requests(url, {
token,
override: {
method: 'POST',
body: JSON.stringify({ tree_id: id, uuid: userId, queryType: 'adopt' }),
body: JSON.stringify({ tree_id: id, uuid: userId }),
},
});

const res = await requests<{ data: Tree[] }>(
createAPIUrl(`/get?&queryType=byid&id=${id}`)
createAPIUrl(`/get/byid?id=${id}`)
);
const tree = res.data[0];

Expand Down
10 changes: 4 additions & 6 deletions src/utils/requests/getCommunityData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ import { createAPIUrl } from '../createAPIUrl';
import { requests } from '../requestUtil';

export const getCommunityData = async (): Promise<CommunityDataType> => {
const fetchCommunityDataUrl = createAPIUrl(
`/get?queryType=wateredandadopted`
);
const fetchCommunityDataUrl = createAPIUrl(`/get/wateredandadopted`);

var json = await requests<{
data: {
tree_id: string;
adopted: string;
watered: string;
adopted: number;
watered: number;
}[];
}>(fetchCommunityDataUrl);

Expand All @@ -26,7 +24,7 @@ export const getCommunityData = async (): Promise<CommunityDataType> => {
const newState = json.data.reduce(
(acc: CommunityDataType, { tree_id: id, adopted, watered }) => {
const item = acc[id];
const isAdopted = item?.adopted || adopted !== '0';
const isAdopted = item?.adopted || adopted !== 0;
const wateredAmount = item?.watered || watered;
return {
communityFlagsMap: {
Expand Down
4 changes: 2 additions & 2 deletions src/utils/requests/getTreeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export const getTreeData = async (
): Promise<{
selectedTreeData: SelectedTreeType | undefined;
}> => {
const urlSelectedTree = createAPIUrl(`/get?queryType=byid&id=${id}`);
const urlWaterings = createAPIUrl(`/get?queryType=lastwatered&id=${id}`);
const urlSelectedTree = createAPIUrl(`/get/byid?id=${id}`);
const urlWaterings = createAPIUrl(`/get/lastwatered?id=${id}`);

const [resSelectedTree, resWaterings] = await Promise.all([
requests<SelectedTreeResponseType>(urlSelectedTree),
Expand Down
4 changes: 1 addition & 3 deletions src/utils/requests/getTreesAdoptedByUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ export const getTreesAdoptedByUser = async ({
userId: string;
token: string;
}): Promise<Tree[]> => {
const urlAdoptedTreesIds = createAPIUrl(
`/get?queryType=adopted&uuid=${userId}`
);
const urlAdoptedTreesIds = createAPIUrl(`/get/adopted?uuid=${userId}`);
const res = await requests<{ data: string[] }>(urlAdoptedTreesIds, { token });
if (!res?.data || res.data.length === 0) return [];
const trees = await getTreesByIds(res.data);
Expand Down
2 changes: 1 addition & 1 deletion src/utils/requests/getTreesByIds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const getTreesByIds = async (ids: string[]): Promise<Tree[]> => {
''
);

const url = createAPIUrl(`/get/?queryType=treesbyids&tree_ids=${queryStr}`);
const url = createAPIUrl(`/get/treesbyids?tree_ids=${queryStr}`);
const res = await requests<{ data: Tree[] }>(url);
return res.data;
};
4 changes: 1 addition & 3 deletions src/utils/requests/getUserWaterings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ export const getUserWaterings = async ({
userId: string;
token: string;
}): Promise<WateringType[]> => {
const urlWateredByUser = createAPIUrl(
`/get?queryType=wateredbyuser&uuid=${userId}`
);
const urlWateredByUser = createAPIUrl(`/get/wateredbyuser?uuid=${userId}`);
const res = await requests<{ data: RawWateringType[] }>(urlWateredByUser, {
token,
});
Expand Down
12 changes: 0 additions & 12 deletions src/utils/requests/getWateredTrees.ts

This file was deleted.

4 changes: 1 addition & 3 deletions src/utils/requests/isTreeAdopted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export async function isTreeAdopted(
): Promise<boolean> {
const { isAuthenticated, uuid, id, token, signal } = opts;
if (!isAuthenticated) return false;
const url = createAPIUrl(
`/get?queryType=istreeadopted&uuid=${uuid}&id=${id}`
);
const url = createAPIUrl(`/get/istreeadopted?uuid=${uuid}&id=${id}`);

const json = await requests<
{ data: IsTreeAdoptedProps },
Expand Down
4 changes: 1 addition & 3 deletions src/utils/requests/unadoptTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ export const unadoptTree = async ({
token: string;
userId: string;
}): Promise<void> => {
const urlUnadopt = createAPIUrl(
`/delete?tree_id=${id}&uuid=${userId}&queryType=unadopt`
);
const urlUnadopt = createAPIUrl(`/delete/unadopt`);

await requests(urlUnadopt, {
token,
Expand Down
3 changes: 1 addition & 2 deletions src/utils/requests/updateWatering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ export const updateWatering = async ({
field: string;
value: string;
}): Promise<boolean> => {
const urlWaterings = createAPIUrl(`/post`);
const urlWaterings = createAPIUrl(`/post/watering-update`);
await requests<undefined, { method: 'POST'; body: string }>(urlWaterings, {
token,
override: {
method: 'POST',
body: JSON.stringify({
queryType: 'watering-update',
watering_id: wateringId,
patches: [{
name: field,
Expand Down
5 changes: 1 addition & 4 deletions src/utils/requests/waterTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ export const waterTree = async ({
username: string;
token: string;
}): Promise<void> => {
const urlPostWatering = createAPIUrl(
`/post?tree_id=${id}&amount=${amount}&timestamp=${timestamp}&uuid=${userId}&token=${token}&username=${username}&queryType=water`
);
const urlPostWatering = createAPIUrl(`/post/water`);

await requests<undefined, { method: 'POST'; body: string }>(urlPostWatering, {
token,
Expand All @@ -30,7 +28,6 @@ export const waterTree = async ({
timestamp,
uuid: userId,
username,
queryType: 'water',
}),
},
});
Expand Down

0 comments on commit 13d11bb

Please sign in to comment.