Skip to content

Commit

Permalink
Merge pull request #44 from HakierGrzonzo/36-usuwanie-plików-z-edytor…
Browse files Browse the repository at this point in the history
…a-+-poprawka-usuwania-pomiarów

36 usuwanie plików z edytora + poprawka usuwania pomiarów
  • Loading branch information
HakierGrzonzo authored Apr 16, 2022
2 parents 3c8c24f + ff84c0a commit acfaac8
Show file tree
Hide file tree
Showing 27 changed files with 226 additions and 194 deletions.
103 changes: 42 additions & 61 deletions frontend/editor/src/api/core/request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import FormData from 'form-data';

import { ApiError } from './ApiError';
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
Expand Down Expand Up @@ -33,8 +36,8 @@ const isBlob = (value: any): value is Blob => {
);
};

const isFormData = (value: any): value is FormData => {
return value instanceof FormData;
const isSuccess = (status: number): boolean => {
return status >= 200 && status < 300;
};

const base64 = (str: string): string => {
Expand Down Expand Up @@ -135,22 +138,24 @@ const resolve = async <T>(options: ApiRequestOptions, resolver?: T | Resolver<T>
return resolver;
};

const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise<Headers> => {
const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise<Record<string, string>> => {
const token = await resolve(options, config.TOKEN);
const username = await resolve(options, config.USERNAME);
const password = await resolve(options, config.PASSWORD);
const additionalHeaders = await resolve(options, config.HEADERS);
const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {}

const headers = Object.entries({
Accept: 'application/json',
...additionalHeaders,
...options.headers,
...formHeaders,
})
.filter(([_, value]) => isDefined(value))
.reduce((headers, [key, value]) => ({
...headers,
[key]: String(value),
}), {} as Record<string, string>);
.filter(([_, value]) => isDefined(value))
.reduce((headers, [key, value]) => ({
...headers,
[key]: String(value),
}), {} as Record<string, string>);

if (isStringWithValue(token)) {
headers['Authorization'] = `Bearer ${token}`;
Expand All @@ -161,86 +166,62 @@ const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Pr
headers['Authorization'] = `Basic ${credentials}`;
}

if (options.body) {
if (options.mediaType) {
headers['Content-Type'] = options.mediaType;
} else if (isBlob(options.body)) {
headers['Content-Type'] = options.body.type || 'application/octet-stream';
} else if (isString(options.body)) {
headers['Content-Type'] = 'text/plain';
} else if (!isFormData(options.body)) {
headers['Content-Type'] = 'application/json';
}
}

return new Headers(headers);
return headers;
};

const getRequestBody = (options: ApiRequestOptions): any => {
if (options.body) {
if (options.mediaType?.includes('/json')) {
return JSON.stringify(options.body)
} else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
return options.body;
} else {
return JSON.stringify(options.body);
}
return options.body;
}
return;
};

export const sendRequest = async (
const sendRequest = async <T>(
config: OpenAPIConfig,
options: ApiRequestOptions,
url: string,
body: any,
formData: FormData | undefined,
headers: Headers,
headers: Record<string, string>,
onCancel: OnCancel
): Promise<Response> => {
const controller = new AbortController();
): Promise<AxiosResponse<T>> => {
const source = axios.CancelToken.source();

const request: RequestInit = {
const requestConfig: AxiosRequestConfig = {
url,
headers,
body: body ?? formData,
data: body ?? formData,
method: options.method,
signal: controller.signal,
withCredentials: config.WITH_CREDENTIALS,
cancelToken: source.token,
};

if (config.WITH_CREDENTIALS) {
request.credentials = config.CREDENTIALS;
}

onCancel(() => controller.abort());
onCancel(() => source.cancel('The user aborted a request.'));

return await fetch(url, request);
try {
return await axios.request(requestConfig);
} catch (error) {
const axiosError = error as AxiosError;
if (axiosError.response) {
return axiosError.response;
}
throw error;
}
};

const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => {
const getResponseHeader = (response: AxiosResponse<any>, responseHeader?: string): string | undefined => {
if (responseHeader) {
const content = response.headers.get(responseHeader);
const content = response.headers[responseHeader];
if (isString(content)) {
return content;
}
}
return;
};

const getResponseBody = async (response: Response): Promise<any> => {
const getResponseBody = (response: AxiosResponse<any>): any => {
if (response.status !== 204) {
try {
const contentType = response.headers.get('Content-Type');
if (contentType) {
const isJSON = contentType.toLowerCase().startsWith('application/json');
if (isJSON) {
return await response.json();
} else {
return await response.text();
}
}
} catch (error) {
console.error(error);
}
return response.data;
}
return;
};
Expand Down Expand Up @@ -280,16 +261,16 @@ export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions): C
const url = getUrl(config, options);
const formData = getFormData(options);
const body = getRequestBody(options);
const headers = await getHeaders(config, options);
const headers = await getHeaders(config, options, formData);

if (!onCancel.isCancelled) {
const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
const responseBody = await getResponseBody(response);
const response = await sendRequest<T>(config, options, url, body, formData, headers, onCancel);
const responseBody = getResponseBody(response);
const responseHeader = getResponseHeader(response, options.responseHeader);

const result: ApiResult = {
url,
ok: response.ok,
ok: isSuccess(response.status),
status: response.status,
statusText: response.statusText,
body: responseHeader ?? responseBody,
Expand Down
1 change: 1 addition & 0 deletions frontend/editor/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';

export type { AdminPanelMsg } from './models/AdminPanelMsg';
export type { backend__errors__ErrorModel } from './models/backend__errors__ErrorModel';
export type { BearerResponse } from './models/BearerResponse';
export type { Body_auth_cookie_login_api_cookie_login_post } from './models/Body_auth_cookie_login_api_cookie_login_post';
Expand Down
7 changes: 7 additions & 0 deletions frontend/editor/src/api/models/AdminPanelMsg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */

export type AdminPanelMsg = {
msg: string;
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/BearerResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
export type BearerResponse = {
access_token: string;
token_type: string;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ export type Body_auth_cookie_login_api_cookie_login_post = {
scope?: string;
client_id?: string;
client_secret?: string;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ export type Body_auth_jwt_login_api_jwt_login_post = {
scope?: string;
client_id?: string;
client_secret?: string;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

export type Body_upload_new_file_api_files__post = {
uploaded_file: Blob;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/CreateMeasurement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ export type CreateMeasurement = {
title: string;
laeq: number;
tags: Array<string>;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/FileReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ export type FileReference = {
measurement: number;
owner: string;
link: string;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/HTTPValidationError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ import type { ValidationError } from './ValidationError';

export type HTTPValidationError = {
detail?: Array<ValidationError>;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/Location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export type Location = {
latitude: number;
longitude: number;
time: string;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/Measurement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ export type Measurement = {
measurement_id: number;
files: Array<FileReference>;
weather?: Weather;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/UpdateMeasurement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ export type UpdateMeasurement = {
title: string;
laeq: number;
tags: Array<string>;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ export type User = {
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/UserCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ export type UserCreate = {
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/UserUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ export type UserUpdate = {
is_active?: boolean;
is_superuser?: boolean;
is_verified?: boolean;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/ValidationError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export type ValidationError = {
loc: Array<string>;
msg: string;
type: string;
};
};
2 changes: 1 addition & 1 deletion frontend/editor/src/api/models/Weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ export type Weather = {
pressure: number;
humidity: number;
status: string;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

export type backend__errors__ErrorModel = {
detail: string;
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

export type fastapi_users__router__common__ErrorModel = {
detail: (string | Record<string, string>);
};
};
14 changes: 7 additions & 7 deletions frontend/editor/src/api/services/AuthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ export class AuthService {

/**
* Auth:Cookie.Login
* @param formData
* @param formData
* @returns any Successful Response
* @throws ApiError
*/
public static authCookieLoginApiCookieLoginPost(
formData: Body_auth_cookie_login_api_cookie_login_post,
): CancelablePromise<any> {
formData: Body_auth_cookie_login_api_cookie_login_post,
): CancelablePromise<any> {
return __request(OpenAPI, {
method: 'POST',
url: '/api/cookie/login',
Expand Down Expand Up @@ -49,13 +49,13 @@ export class AuthService {

/**
* Auth:Jwt.Login
* @param formData
* @param formData
* @returns BearerResponse Successful Response
* @throws ApiError
*/
public static authJwtLoginApiJwtLoginPost(
formData: Body_auth_jwt_login_api_jwt_login_post,
): CancelablePromise<BearerResponse> {
formData: Body_auth_jwt_login_api_jwt_login_post,
): CancelablePromise<BearerResponse> {
return __request(OpenAPI, {
method: 'POST',
url: '/api/jwt/login',
Expand Down Expand Up @@ -85,7 +85,7 @@ export class AuthService {

/**
* Tea
* @returns void
* @returns void
* @throws ApiError
*/
public static teaApiAuthGet(): CancelablePromise<void> {
Expand Down
Loading

0 comments on commit acfaac8

Please sign in to comment.