kibana/examples/routing_example/public/services.ts
Gerard Soldevila 4824d9da8c
Migrate types to packages: Client-side HTTP service (#135562)
* Migrate types to packages: Client-side HTTP service

* Fix linting issues, compactify some imports

* Fix incorrect typing, remove unnecessary exports

* Remove unnecessary export

* Fix trailing spaces removed by mistake

* Move Sha256 to new @kbn/crypto-browser package

* Support deprecated 'req' property in isHttpFetchError() method

* Fix failing UT in lens

* Update API docs

* Reorder imports, absolute imports first

* Provide createHttpFetchError() convenience method

* Fix typing issue

* Fix rebase issues

* Fix incorrect import

* Avod using core internals for plugin testing

* Fix automerge issues

* Misc enhancements following PR review
2022-07-11 12:25:55 -07:00

68 lines
2.2 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { CoreStart } from '@kbn/core/public';
import type { IHttpFetchError } from '@kbn/core-http-browser';
import {
RANDOM_NUMBER_ROUTE_PATH,
RANDOM_NUMBER_BETWEEN_ROUTE_PATH,
POST_MESSAGE_ROUTE_PATH,
INTERNAL_GET_MESSAGE_BY_ID_ROUTE,
} from '../common';
export interface Services {
fetchRandomNumber: () => Promise<number | IHttpFetchError>;
fetchRandomNumberBetween: (max: number) => Promise<number | IHttpFetchError>;
postMessage: (message: string, id: string) => Promise<undefined | IHttpFetchError>;
getMessageById: (id: string) => Promise<string | IHttpFetchError>;
addSuccessToast: (message: string) => void;
}
export function getServices(core: CoreStart): Services {
return {
addSuccessToast: (message: string) => core.notifications.toasts.addSuccess(message),
fetchRandomNumber: async () => {
try {
const response = await core.http.fetch<{ randomNumber: number }>(RANDOM_NUMBER_ROUTE_PATH);
return response.randomNumber;
} catch (e) {
return e;
}
},
fetchRandomNumberBetween: async (max: number) => {
try {
const response = await core.http.fetch<{ randomNumber: number }>(
RANDOM_NUMBER_BETWEEN_ROUTE_PATH,
{ query: { max } }
);
return response.randomNumber;
} catch (e) {
return e;
}
},
postMessage: async (message: string, id: string) => {
try {
await core.http.post(`${POST_MESSAGE_ROUTE_PATH}/${id}`, {
body: JSON.stringify({ message }),
});
} catch (e) {
return e;
}
},
getMessageById: async (id: string) => {
try {
const response = await core.http.get<{ message: string }>(
`${INTERNAL_GET_MESSAGE_BY_ID_ROUTE}/${id}`
);
return response.message;
} catch (e) {
return e;
}
},
};
}