API client generation: create a central `getAPIBaseURL` function (#99961)

* create a getAPIBaseURL function

* use base url in iam api
pull/99952/head^2
Ashley Harrison 4 months ago committed by GitHub
parent c85a175212
commit 30bf2bcde1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 10
      public/app/api/utils.ts
  2. 2
      public/app/core/reducers/root.ts
  3. 2
      public/app/features/explore/QueryLibrary/QueryLibraryDrawer.tsx
  4. 6
      public/app/features/iam/api/api.ts
  5. 5
      public/app/features/query-library/api/api.ts
  6. 36
      public/app/features/query-library/api/endpoints.gen.ts
  7. 3
      public/app/features/query-library/api/mappers.ts
  8. 2
      public/app/features/query-library/api/mocks.ts
  9. 20
      public/app/features/query-library/api/query.ts
  10. 2
      public/app/features/query-library/index.ts
  11. 2
      public/app/store/configureStore.ts

@ -1,3 +1,13 @@
import { config } from '@grafana/runtime';
export const getAPINamespace = () => config.namespace;
/**
* Get a base URL for a k8s API endpoint with parameterised namespace given it's group and version
* @param group the k8s group, e.g. dashboard.grafana.app
* @param version e.g. v0alpha1
* @returns
*/
export const getAPIBaseURL = (group: string, version: string) => {
return `/apis/${group}/${version}/namespaces/${getAPINamespace()}`;
};

@ -30,7 +30,7 @@ import templatingReducers from 'app/features/variables/state/keyedVariablesReduc
import { alertingApi } from '../../features/alerting/unified/api/alertingApi';
import { iamApi } from '../../features/iam/api/api';
import { userPreferencesAPI } from '../../features/preferences/api';
import { queryLibraryApi } from '../../features/query-library/api/factory';
import { queryLibraryApi } from '../../features/query-library/api/api';
import { cleanUpAction } from '../actions/cleanUp';
const rootReducers = {

@ -5,7 +5,7 @@ import { TabbedContainer, TabConfig } from '@grafana/ui';
import { t } from '../../../core/internationalization';
import { useListQueryTemplateQuery } from '../../query-library';
import { QUERY_LIBRARY_GET_LIMIT } from '../../query-library/api/factory';
import { QUERY_LIBRARY_GET_LIMIT } from '../../query-library/api/api';
import { ExploreDrawer } from '../ExploreDrawer';
import { QueryLibrary } from './QueryLibrary';

@ -1,11 +1,9 @@
import { createApi } from '@reduxjs/toolkit/query/react';
import { createBaseQuery } from '../../../api/createBaseQuery';
import { getAPINamespace } from '../../../api/utils';
import { getAPIBaseURL } from '../../../api/utils';
export const API_VERSION = 'iam.grafana.app/v0alpha1';
export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getAPINamespace()}`;
export const BASE_URL = getAPIBaseURL('iam.grafana.app', 'v0alpha1');
export const iamApi = createApi({
baseQuery: createBaseQuery({ baseURL: BASE_URL }),

@ -1,13 +1,14 @@
import { createApi } from '@reduxjs/toolkit/query/react';
import { createBaseQuery } from '../../../api/createBaseQuery';
import { BASE_URL } from './query';
import { getAPIBaseURL } from '../../../api/utils';
// Currently, we are loading all query templates
// Organizations can have maximum of 1000 query templates
export const QUERY_LIBRARY_GET_LIMIT = 1000;
export const BASE_URL = getAPIBaseURL('peakq.grafana.app', 'v0alpha1');
export const queryLibraryApi = createApi({
baseQuery: createBaseQuery({ baseURL: BASE_URL }),
reducerPath: 'queryLibraryAPI',

@ -1,4 +1,4 @@
import { queryLibraryApi as api } from './factory';
import { queryLibraryApi as api } from './api';
export const addTagTypes = ['QueryTemplate'] as const;
const injectedRtkApi = api
.enhanceEndpoints({
@ -81,7 +81,7 @@ export type ListQueryTemplateApiArg = {
/** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */
allowWatchBookmarks?: boolean;
/** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key".
This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */
continue?: string;
/** A selector to restrict the list of returned objects by their fields. Defaults to everything. */
@ -89,19 +89,19 @@ export type ListQueryTemplateApiArg = {
/** A selector to restrict the list of returned objects by their labels. Defaults to everything. */
labelSelector?: string;
/** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.
The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */
limit?: number;
/** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersion?: string;
/** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.
Defaults to unset */
resourceVersionMatch?: string;
/** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.
When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan
is interpreted as "data at least as new as the provided `resourceVersion`"
and the bookmark event is send when the state is synced
@ -111,7 +111,7 @@ export type ListQueryTemplateApiArg = {
when request started being processed.
- `resourceVersionMatch` set to any other value or unset
Invalid error is returned.
Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */
sendInitialEvents?: boolean;
/** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */
@ -208,21 +208,21 @@ export type ObjectMeta = {
[key: string]: string;
};
/** CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.
Populated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
creationTimestamp?: Time;
/** Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only. */
deletionGracePeriodSeconds?: number;
/** DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.
Populated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */
deletionTimestamp?: Time;
/** Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list. */
finalizers?: string[];
/** GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
If this field is specified and the generated name exists, the server will return a 409.
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */
generateName?: string;
/** A sequence number representing a specific generation of the desired state. Populated by the system. Read-only. */
@ -236,19 +236,19 @@ export type ObjectMeta = {
/** Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names */
name?: string;
/** Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces */
namespace?: string;
/** List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller. */
ownerReferences?: OwnerReference[];
/** An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */
resourceVersion?: string;
/** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */
selfLink?: string;
/** UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */
uid?: string;
};
@ -284,8 +284,8 @@ export type DataQuery = {
/** Maximum frame count */
maxFrames?: number;
/** Type asserts that the frame matches a known type structure.
Possible enum values:
- `""`
- `"timeseries-wide"`
@ -333,7 +333,7 @@ export type TemplatePosition = {
};
export type TemplateVariableReplacement = {
/** How values should be interpolated
Possible enum values:
- `"csv"` Formats variables with multiple values as a comma-separated string.
- `"doublequote"` Formats single- and multi-valued variables into a comma-separated string
@ -406,7 +406,7 @@ export type QueryTemplateList = {
};
export type StatusCause = {
/** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.
Examples:
"name" - the field "name" on the current resource
"items[0].name" - the field "name" on the first array entry in "items" */

@ -4,7 +4,6 @@ import { AnnoKeyCreatedBy } from '../../apiserver/types';
import { AddQueryTemplateCommand, QueryTemplate } from '../types';
import { ListQueryTemplateApiResponse, QueryTemplate as QT } from './endpoints.gen';
import { API_VERSION, QueryTemplateKinds } from './query';
export const convertDataQueryResponseToQueryTemplates = (result: ListQueryTemplateApiResponse): QueryTemplate[] => {
if (!result.items) {
@ -30,8 +29,6 @@ export const convertDataQueryResponseToQueryTemplates = (result: ListQueryTempla
export const convertAddQueryTemplateCommandToDataQuerySpec = (addQueryTemplateCommand: AddQueryTemplateCommand): QT => {
const { title, targets } = addQueryTemplateCommand;
return {
apiVersion: API_VERSION,
kind: QueryTemplateKinds.QueryTemplate,
metadata: {
/**
* Server will append to whatever is passed here, but just to be safe we generate a uuid

@ -1,4 +1,4 @@
import { BASE_URL } from './query';
import { BASE_URL } from './api';
import { getIdentityDisplayList } from './testdata/identityDisplayList';
import { getTestQueryList } from './testdata/testQueryList';

@ -1,20 +0,0 @@
import { getAPINamespace } from '../../../api/utils';
/**
* @alpha
*/
export const API_VERSION = 'peakq.grafana.app/v0alpha1';
/**
* @alpha
*/
export enum QueryTemplateKinds {
QueryTemplate = 'QueryTemplate',
}
/**
* Query Library is an experimental feature. API (including the URL path) will likely change.
*
* @alpha
*/
export const BASE_URL = `/apis/${API_VERSION}/namespaces/${getAPINamespace()}`;

@ -9,8 +9,8 @@
import { config } from '@grafana/runtime';
import { QUERY_LIBRARY_GET_LIMIT } from './api/api';
import { generatedQueryLibraryApi } from './api/endpoints.gen';
import { QUERY_LIBRARY_GET_LIMIT } from './api/factory';
import { mockData } from './api/mocks';
export const {

@ -12,7 +12,7 @@ import { buildInitialState } from '../core/reducers/navModel';
import { addReducer, createRootReducer } from '../core/reducers/root';
import { alertingApi } from '../features/alerting/unified/api/alertingApi';
import { iamApi } from '../features/iam/api/api';
import { queryLibraryApi } from '../features/query-library/api/factory';
import { queryLibraryApi } from '../features/query-library/api/api';
import { setStore } from './store';

Loading…
Cancel
Save