Apply prettier rules

This commit is contained in:
2024-11-14 18:47:38 +01:00
parent 610227815a
commit aa0785fc71
291 changed files with 23646 additions and 22071 deletions

View File

@@ -1,35 +1,61 @@
import {Address, GeographicalUnitLayer, SimpleGeographicalUnit} from "../../types";
import {fetchResults, makeFetch} from "./apiMethods";
import {
Address,
GeographicalUnitLayer,
SimpleGeographicalUnit,
} from "../../types";
import { fetchResults, makeFetch } from "./apiMethods";
export const getAddressById = async (address_id: number): Promise<Address> =>
{
const url = `/api/1.0/main/address/${address_id}.json`;
export const getAddressById = async (address_id: number): Promise<Address> => {
const url = `/api/1.0/main/address/${address_id}.json`;
const response = await fetch(url);
const response = await fetch(url);
if (response.ok) {
return response.json();
}
if (response.ok) {
return response.json();
}
throw Error('Error with request resource response');
throw Error("Error with request resource response");
};
export const getGeographicalUnitsByAddress = async (address: Address): Promise<SimpleGeographicalUnit[]> => {
return fetchResults<SimpleGeographicalUnit>(`/api/1.0/main/geographical-unit/by-address/${address.address_id}.json`);
}
export const getGeographicalUnitsByAddress = async (
address: Address,
): Promise<SimpleGeographicalUnit[]> => {
return fetchResults<SimpleGeographicalUnit>(
`/api/1.0/main/geographical-unit/by-address/${address.address_id}.json`,
);
};
export const getAllGeographicalUnitLayers = async (): Promise<GeographicalUnitLayer[]> => {
return fetchResults<GeographicalUnitLayer>(`/api/1.0/main/geographical-unit-layer.json`);
}
export const getAllGeographicalUnitLayers = async (): Promise<
GeographicalUnitLayer[]
> => {
return fetchResults<GeographicalUnitLayer>(
`/api/1.0/main/geographical-unit-layer.json`,
);
};
export const syncAddressWithReference = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/sync-with-reference`);
}
export const syncAddressWithReference = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/sync-with-reference`,
);
};
export const markAddressReviewed = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/set/reviewed`);
}
export const markAddressReviewed = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/set/reviewed`,
);
};
export const markAddressToReview = async (address: Address): Promise<Address> => {
return makeFetch<null, Address>("POST", `/api/1.0/main/address/reference-match/${address.address_id}/set/to_review`);
}
export const markAddressToReview = async (
address: Address,
): Promise<Address> => {
return makeFetch<null, Address>(
"POST",
`/api/1.0/main/address/reference-match/${address.address_id}/set/to_review`,
);
};

View File

@@ -1,58 +1,61 @@
import {Scope} from '../../types';
import { Scope } from "../../types";
export type body = Record<string, boolean|string|number|null>;
export type fetchOption = Record<string, boolean|string|number|null>;
export type body = Record<string, boolean | string | number | null>;
export type fetchOption = Record<string, boolean | string | number | null>;
export type Params = Record<string, number|string>;
export type Params = Record<string, number | string>;
export interface PaginationResponse<T> {
pagination: {
more: boolean;
items_per_page: number;
};
results: T[];
count: number;
pagination: {
more: boolean;
items_per_page: number;
};
results: T[];
count: number;
}
export type FetchParams = Record<string, string|number|null>;;
export type FetchParams = Record<string, string | number | null>;
export interface TransportExceptionInterface {
name: string;
name: string;
}
export interface ValidationExceptionInterface extends TransportExceptionInterface {
name: 'ValidationException';
error: object;
violations: string[];
titles: string[];
propertyPaths: string[];
export interface ValidationExceptionInterface
extends TransportExceptionInterface {
name: "ValidationException";
error: object;
violations: string[];
titles: string[];
propertyPaths: string[];
}
export interface ValidationErrorResponse extends TransportExceptionInterface {
violations: {
title: string;
propertyPath: string;
}[];
violations: {
title: string;
propertyPath: string;
}[];
}
export interface AccessExceptionInterface extends TransportExceptionInterface {
name: 'AccessException';
violations: string[];
name: "AccessException";
violations: string[];
}
export interface NotFoundExceptionInterface extends TransportExceptionInterface {
name: 'NotFoundException';
export interface NotFoundExceptionInterface
extends TransportExceptionInterface {
name: "NotFoundException";
}
export interface ServerExceptionInterface extends TransportExceptionInterface {
name: 'ServerException';
message: string;
code: number;
body: string;
name: "ServerException";
message: string;
code: number;
body: string;
}
export interface ConflictHttpExceptionInterface extends TransportExceptionInterface {
name: 'ConflictHttpException';
export interface ConflictHttpExceptionInterface
extends TransportExceptionInterface {
name: "ConflictHttpException";
violations: string[];
}
@@ -60,35 +63,33 @@ export interface ConflictHttpExceptionInterface extends TransportExceptionInterf
* Generic api method that can be adapted to any fetch request
*/
export const makeFetch = <Input, Output>(
method: 'POST'|'GET'|'PUT'|'PATCH'|'DELETE',
url: string, body?: body | Input | null,
options?: FetchParams
method: "POST" | "GET" | "PUT" | "PATCH" | "DELETE",
url: string,
body?: body | Input | null,
options?: FetchParams,
): Promise<Output> => {
let opts = {
method: method,
headers: {
'Content-Type': 'application/json;charset=utf-8'
"Content-Type": "application/json;charset=utf-8",
},
};
if (body !== null && typeof body !== 'undefined') {
Object.assign(opts, {body: JSON.stringify(body)})
if (body !== null && typeof body !== "undefined") {
Object.assign(opts, { body: JSON.stringify(body) });
}
if (typeof options !== 'undefined') {
if (typeof options !== "undefined") {
opts = Object.assign(opts, options);
}
return fetch(url, opts)
.then(response => {
return fetch(url, opts).then((response) => {
if (response.ok) {
return response.json();
}
if (response.status === 422) {
return response.json().then(response => {
throw ValidationException(response)
return response.json().then((response) => {
throw ValidationException(response);
});
}
@@ -101,79 +102,94 @@ export const makeFetch = <Input, Output>(
}
throw {
name: 'Exception',
name: "Exception",
sta: response.status,
txt: response.statusText,
err: new Error(),
violations: response.body
violations: response.body,
};
});
}
};
/**
* Fetch results with certain parameters
*/
function _fetchAction<T>(page: number, uri: string, params?: FetchParams): Promise<PaginationResponse<T>> {
function _fetchAction<T>(
page: number,
uri: string,
params?: FetchParams,
): Promise<PaginationResponse<T>> {
const item_per_page = 50;
const searchParams = new URLSearchParams();
searchParams.append('item_per_page', item_per_page.toString());
searchParams.append('page', page.toString());
searchParams.append("item_per_page", item_per_page.toString());
searchParams.append("page", page.toString());
if (params !== undefined) {
Object.keys(params).forEach(key => {
const v = params[key];
if (typeof v === 'string') {
searchParams.append(key, v);
} else if (typeof v === 'number') {
searchParams.append(key, v.toString());
} else if (v === null) {
searchParams.append(key, '');
}
});
Object.keys(params).forEach((key) => {
const v = params[key];
if (typeof v === "string") {
searchParams.append(key, v);
} else if (typeof v === "number") {
searchParams.append(key, v.toString());
} else if (v === null) {
searchParams.append(key, "");
}
});
}
const url = uri + '?' + searchParams.toString();
const url = uri + "?" + searchParams.toString();
return fetch(url, {
method: 'GET',
method: "GET",
headers: {
'Content-Type': 'application/json;charset=utf-8'
"Content-Type": "application/json;charset=utf-8",
},
}).then((response) => {
if (response.ok) { return response.json(); }
})
.then((response) => {
if (response.ok) {
return response.json();
}
if (response.status === 404) {
throw NotFoundException(response);
}
if (response.status === 404) {
throw NotFoundException(response);
}
if (response.status === 422) {
return response.json().then(response => {
throw ValidationException(response)
});
}
if (response.status === 422) {
return response.json().then((response) => {
throw ValidationException(response);
});
}
if (response.status === 403) {
throw AccessException(response);
}
if (response.status === 403) {
throw AccessException(response);
}
if (response.status >= 500) {
return response.text().then(body => {
throw ServerException(response.status, body);
});
}
if (response.status >= 500) {
return response.text().then((body) => {
throw ServerException(response.status, body);
});
}
throw new Error("other network error");
}).catch((reason: any) => {
console.error(reason);
throw new Error(reason);
});
};
throw new Error("other network error");
})
.catch((reason: any) => {
console.error(reason);
throw new Error(reason);
});
}
export const fetchResults = async<T> (uri: string, params?: FetchParams): Promise<T[]> => {
export const fetchResults = async <T>(
uri: string,
params?: FetchParams,
): Promise<T[]> => {
let promises: Promise<T[]>[] = [],
page = 1;
const firstData: PaginationResponse<T> = await _fetchAction(page, uri, params) as PaginationResponse<T>;
const firstData: PaginationResponse<T> = (await _fetchAction(
page,
uri,
params,
)) as PaginationResponse<T>;
promises.push(Promise.resolve(firstData.results));
@@ -181,61 +197,74 @@ export const fetchResults = async<T> (uri: string, params?: FetchParams): Promis
do {
page = ++page;
promises.push(
_fetchAction<T>(page, uri, params)
.then(r => Promise.resolve(r.results))
_fetchAction<T>(page, uri, params).then((r) =>
Promise.resolve(r.results),
),
);
} while (page * firstData.pagination.items_per_page < firstData.count)
} while (page * firstData.pagination.items_per_page < firstData.count);
}
return Promise.all(promises).then((values) => values.flat());
};
export const fetchScopes = (): Promise<Scope[]> => {
return fetchResults('/api/1.0/main/scope.json');
return fetchResults("/api/1.0/main/scope.json");
};
/**
* Error objects to be thrown
*/
const ValidationException = (response: ValidationErrorResponse): ValidationExceptionInterface => {
const ValidationException = (
response: ValidationErrorResponse,
): ValidationExceptionInterface => {
const error = {} as ValidationExceptionInterface;
error.name = 'ValidationException';
error.violations = response.violations.map((violation) => `${violation.title}: ${violation.propertyPath}`);
error.name = "ValidationException";
error.violations = response.violations.map(
(violation) => `${violation.title}: ${violation.propertyPath}`,
);
error.titles = response.violations.map((violation) => violation.title);
error.propertyPaths = response.violations.map((violation) => violation.propertyPath);
error.propertyPaths = response.violations.map(
(violation) => violation.propertyPath,
);
return error;
}
};
const AccessException = (response: Response): AccessExceptionInterface => {
const error = {} as AccessExceptionInterface;
error.name = 'AccessException';
error.violations = ['You are not allowed to perform this action'];
error.name = "AccessException";
error.violations = ["You are not allowed to perform this action"];
return error;
}
};
const NotFoundException = (response: Response): NotFoundExceptionInterface => {
const error = {} as NotFoundExceptionInterface;
error.name = 'NotFoundException';
return error;
}
const ServerException = (code: number, body: string): ServerExceptionInterface => {
const error = {} as ServerExceptionInterface;
error.name = 'ServerException';
error.code = code;
error.body = body;
return error;
}
const ConflictHttpException = (response: Response): ConflictHttpExceptionInterface => {
const error = {} as ConflictHttpExceptionInterface;
error.name = 'ConflictHttpException';
error.violations = ['Sorry, but someone else has already changed this entity. Please refresh the page and apply the changes again']
const error = {} as NotFoundExceptionInterface;
error.name = "NotFoundException";
return error;
}
};
const ServerException = (
code: number,
body: string,
): ServerExceptionInterface => {
const error = {} as ServerExceptionInterface;
error.name = "ServerException";
error.code = code;
error.body = body;
return error;
};
const ConflictHttpException = (
response: Response,
): ConflictHttpExceptionInterface => {
const error = {} as ConflictHttpExceptionInterface;
error.name = "ConflictHttpException";
error.violations = [
"Sorry, but someone else has already changed this entity. Please refresh the page and apply the changes again",
];
return error;
};

View File

@@ -1,4 +1,3 @@
// const _fetchAction = (page, uri, params) => {
// const item_per_page = 50;
// if (params === undefined) {

View File

@@ -1,6 +1,8 @@
import {fetchResults} from "./apiMethods";
import {Location, LocationType} from "../../types";
import { fetchResults } from "./apiMethods";
import { Location, LocationType } from "../../types";
export const getLocations = (): Promise<Location[]> => fetchResults('/api/1.0/main/location.json');
export const getLocations = (): Promise<Location[]> =>
fetchResults("/api/1.0/main/location.json");
export const getLocationTypes = (): Promise<LocationType[]> => fetchResults('/api/1.0/main/location-type.json');
export const getLocationTypes = (): Promise<LocationType[]> =>
fetchResults("/api/1.0/main/location-type.json");

View File

@@ -1,25 +1,24 @@
import {User} from "../../types";
import {makeFetch} from "./apiMethods";
import { User } from "../../types";
import { makeFetch } from "./apiMethods";
export const whoami = (): Promise<User> => {
const url = `/api/1.0/main/whoami.json`;
return fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw {
msg: 'Error while getting whoami.',
sta: response.status,
txt: response.statusText,
err: new Error(),
body: response.body
};
const url = `/api/1.0/main/whoami.json`;
return fetch(url).then((response) => {
if (response.ok) {
return response.json();
}
throw {
msg: "Error while getting whoami.",
sta: response.status,
txt: response.statusText,
err: new Error(),
body: response.body,
};
});
};
export const whereami = (): Promise<Location | null> => {
const url = `/api/1.0/main/user-current-location.json`;
const url = `/api/1.0/main/user-current-location.json`;
return makeFetch<null, Location|null>("GET", url);
}
return makeFetch<null, Location | null>("GET", url);
};