Skip to content

Commit

Permalink
refactor: rename resolve function for clarity
Browse files Browse the repository at this point in the history
  • Loading branch information
mainawycliffe authored and moshloop committed Aug 18, 2024
1 parent 63a3825 commit c415667
Show file tree
Hide file tree
Showing 16 changed files with 169 additions and 107 deletions.
14 changes: 11 additions & 3 deletions src/api/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,17 @@ export type ApiResp<T = any> = Promise<
}
>;

export const resolve: <T>(promise: AxiosPromise<T>) => ApiResp<T> = async (
promise
) => {
/**
*
* Takes a response from postgrest and extracts the pagination information from
* headers and adds it to the response object.
*
* https://docs.postgrest.org/en/v12/references/api/pagination_count.html
*
*/
export const resolvePostGrestRequestWithPagination: <T>(
promise: AxiosPromise<T>
) => ApiResp<T> = async (promise) => {
try {
const { data, headers } = await promise;
const hasContentRangeHeader = !!headers["content-range"]?.trim();
Expand Down
4 changes: 2 additions & 2 deletions src/api/schemaResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { AxiosResponse } from "axios";
import { AVATAR_INFO } from "../constants";
import { CanaryCheckerDB, ConfigDB, IncidentCommander } from "./axios";
import { resolve } from "./resolve";
import { resolvePostGrestRequestWithPagination } from "./resolve";
import { ConfigItem } from "./types/configs";

export interface SchemaResourceI {
Expand Down Expand Up @@ -178,7 +178,7 @@ export async function getIntegrationsWithJobStatus(
) {
const pagingParams = `&limit=${pageSize}&offset=${pageIndex * pageSize}`;

const res = await resolve(
const res = await resolvePostGrestRequestWithPagination(
CanaryCheckerDB.get<SchemaResourceWithJobStatus[] | null>(
// todo: add back created_by
`integrations_with_status?order=created_at.desc&select=*&deleted_at=is.null${pagingParams}`,
Expand Down
4 changes: 2 additions & 2 deletions src/api/services/agents.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Agent, AgentSummary } from "../../components/Agents/AgentPage";
import { AVATAR_INFO } from "../../constants";
import { AgentAPI, IncidentCommander } from "../axios";
import { resolve } from "../resolve";
import { resolvePostGrestRequestWithPagination } from "../resolve";
import { AgentItem } from "../types/common";

export const Local = "00000000-0000-0000-0000-000000000000";
Expand All @@ -23,7 +23,7 @@ export const getAgentsList = async (
pageIndex || pageSize
? `&limit=${pageSize}&offset=${pageIndex! * pageSize!}`
: "";
return resolve(
return resolvePostGrestRequestWithPagination(
IncidentCommander.get<AgentSummary[] | null>(
`/agents_summary?select=*,created_by(${AVATAR_INFO})&order=created_at.desc&${pagingParamsStr}${sortByParam}${sortOrderParam}`,
{
Expand Down
9 changes: 4 additions & 5 deletions src/api/services/comments.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { IncidentCommander } from "../axios";
import { resolve } from "../resolve";
import { NewComment } from "../types/incident";
import { Comment } from "../types/incident";
import { resolvePostGrestRequestWithPagination } from "../resolve";
import { Comment, NewComment } from "../types/incident";

export const getCommentsByHypothesis = (hypothesisId: string) =>
resolve<Comment[]>(
resolvePostGrestRequestWithPagination<Comment[]>(
IncidentCommander.get(
`/comments?select=*,created_by(id,name,avatar)&hypothesis_id=eq.${hypothesisId}&order=created_at.asc`
)
Expand All @@ -16,7 +15,7 @@ export const createComment = async ({
hypothesisId,
comment
}: NewComment) =>
resolve<Comment>(
resolvePostGrestRequestWithPagination<Comment>(
IncidentCommander.post(`/comments`, {
created_by: user.id,
incident_id: incidentId,
Expand Down
78 changes: 47 additions & 31 deletions src/api/services/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
} from "@flanksource-ui/ui/Dropdowns/TristateReactSelect";
import { AnyMessageParams } from "yup/lib/types";
import { Catalog, Config, ConfigDB, IncidentCommander } from "../axios";
import { resolve } from "../resolve";
import { resolvePostGrestRequestWithPagination } from "../resolve";
import { PaginationInfo } from "../types/common";
import {
ConfigAnalysis,
Expand All @@ -16,7 +16,7 @@ import {
} from "../types/configs";

export const getAllConfigs = () =>
resolve<ConfigItem[]>(ConfigDB.get(`/configs`));
resolvePostGrestRequestWithPagination<ConfigItem[]>(ConfigDB.get(`/configs`));

export const getConfigsTags = async () => {
const res =
Expand All @@ -29,12 +29,12 @@ export const getAllConfigsMatchingQuery = (query: string) => {
if (query) {
url = `${url}&${query}`;
}
return resolve<ConfigItem[]>(ConfigDB.get(url));
return resolvePostGrestRequestWithPagination<ConfigItem[]>(ConfigDB.get(url));
};

export const getAllConfigsForSearchPurpose = async () => {
let url = `/configs?select=id,name,config_class,type`;
const res = await resolve<
const res = await resolvePostGrestRequestWithPagination<
Pick<ConfigItem, "name" | "config_class" | "type" | "id">[]
>(ConfigDB.get(url));

Expand Down Expand Up @@ -70,7 +70,7 @@ export const getConfigsSummary = async (request: ConfigSummaryRequest) => {
};

export const getConfigsByIDs = async (ids: string[]) => {
const res = await resolve<ConfigItem[] | null>(
const res = await resolvePostGrestRequestWithPagination<ConfigItem[] | null>(
ConfigDB.get(
`/configs?id=in.(${ids.join(",")})&select=id,name,config_class,type`
)
Expand All @@ -79,7 +79,7 @@ export const getConfigsByIDs = async (ids: string[]) => {
};

export const getConfigsByID = async (id: string) => {
const res = await resolve<ConfigItem[] | null>(
const res = await resolvePostGrestRequestWithPagination<ConfigItem[] | null>(
ConfigDB.get(`/configs?id=eq.${id}&select=id,name,config_class,type`)
);
if (res.data && res.data.length > 0) {
Expand Down Expand Up @@ -125,7 +125,7 @@ export const getAllChanges = (
queryString += `&and=(created_at.gte.${startsAt},created_at.lte.${endsAt})`;
}

return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<ConfigChange[]>(
`/config_changes_items?order=created_at.desc${pagingParams}&select=id,change_type,summary,source,created_at,config_id,config:config_names!inner(id,name,type)${queryString}`,
{
Expand All @@ -138,7 +138,7 @@ export const getAllChanges = (
};

export const getConfig = (id: string) =>
resolve<ConfigItem[]>(
resolvePostGrestRequestWithPagination<ConfigItem[]>(
ConfigDB.get(`/config_detail?id=eq.${id}&select=*,config_scrapers(id,name)`)
);

Expand All @@ -152,10 +152,14 @@ export const getConfigTagsList = () => {
};

export const getConfigLabelsList = () =>
resolve<ConfigsTagList[] | null>(ConfigDB.get(`/config_labels`));
resolvePostGrestRequestWithPagination<ConfigsTagList[] | null>(
ConfigDB.get(`/config_labels`)
);

export const getConfigName = (id: string) =>
resolve<ConfigItem[]>(ConfigDB.get(`/config_names?id=eq.${id}`));
resolvePostGrestRequestWithPagination<ConfigItem[]>(
ConfigDB.get(`/config_names?id=eq.${id}`)
);

export const getConfigChanges = (
id: string,
Expand All @@ -178,7 +182,7 @@ export const getConfigChanges = (
if (starts_at && ends_at) {
paginationQueryParams += `&and=(created_at.gte.${starts_at},created_at.lte.${ends_at})`;
}
return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<ConfigChange[]>(
`/config_changes?config_id=eq.${id}&order=created_at.desc${paginationQueryParams}`,
{
Expand Down Expand Up @@ -331,7 +335,9 @@ export async function getConfigsChanges({
}

export const getConfigListFilteredByType = (types: string[]) => {
return resolve<Pick<ConfigItem, "id" | "name" | "config_class" | "type">[]>(
return resolvePostGrestRequestWithPagination<
Pick<ConfigItem, "id" | "name" | "config_class" | "type">[]
>(
ConfigDB.get(
`/config_items?select=id,name,type,config_class${
// if type is not provided, return all configs
Expand Down Expand Up @@ -362,14 +368,14 @@ export const getConfigsBy = ({
const configFields = `id, type, name, config_class, deleted_at`;
const deletedAt = hideDeleted ? `&deleted_at=is.null` : "";
if (topologyId) {
return resolve<ConfigTypeRelationships[]>(
return resolvePostGrestRequestWithPagination<ConfigTypeRelationships[]>(
ConfigDB.get(
`/config_component_relationships?component_id=eq.${topologyId}&configs.order=name&select=*,configs!config_component_relationships_config_id_fkey(${configFields})${deletedAt}`
)
);
}
if (configId) {
return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<ConfigTypeRelationships[]>(
`/config_relationships?or=(related_id.eq.${configId},config_id.eq.${configId})&configs.order=name&select=*,configs:configs!config_relationships_config_id_fkey(${configFields}),related:configs!config_relationships_related_id_fkey(${configFields})${deletedAt}`
)
Expand Down Expand Up @@ -468,7 +474,7 @@ export const addManualComponentConfigRelationship = (
topologyId: string,
configId: string
) => {
return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.post(`/config_component_relationships`, {
component_id: topologyId,
config_id: configId,
Expand All @@ -481,7 +487,7 @@ export const removeManualComponentConfigRelationship = (
topologyId: string,
configId: string
) => {
return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.delete(
`/config_component_relationships?component_id=eq.${topologyId}&config_id=eq.${configId}&selector_id=eq.manual`
)
Expand All @@ -492,55 +498,65 @@ export const searchConfigs = (type: string, input: string) => {
const orCondition = input
? `&or=(name.ilike.*${input}*,external_id.ilike.*${input}*)`
: "";
return resolve<ConfigItem[]>(
return resolvePostGrestRequestWithPagination<ConfigItem[]>(
ConfigDB.get(
`/configs?select=id,external_id,name,type,analysis,changes&type=ilike.${type}${orCondition}`
)
);
};

export const createConfigItem = (type: string, params: {}) =>
resolve<ConfigItem>(
resolvePostGrestRequestWithPagination<ConfigItem>(
ConfigDB.post(`/config_item`, {
type: type,
...params
})
);

export const updateConfigItem = (id: string, params: {}) =>
resolve<ConfigItem>(
resolvePostGrestRequestWithPagination<ConfigItem>(
ConfigDB.patch(`/config_item?id=eq.${id}`, { ...params })
);

export const deleteConfigItem = (id: string) =>
resolve(ConfigDB.delete(`/config_item?id=eq.${id}`));
resolvePostGrestRequestWithPagination(
ConfigDB.delete(`/config_item?id=eq.${id}`)
);

// Saved Queries

export const getAllSavedQueries = () =>
resolve(ConfigDB.get<AnyMessageParams>(`/saved_query`));
resolvePostGrestRequestWithPagination(
ConfigDB.get<AnyMessageParams>(`/saved_query`)
);

export const getSavedQuery = (id: string) =>
resolve(ConfigDB.get(`/saved_query?id=eq.${id}`));
resolvePostGrestRequestWithPagination(
ConfigDB.get(`/saved_query?id=eq.${id}`)
);

export const createSavedQuery = (query: string, params: any) =>
resolve(
resolvePostGrestRequestWithPagination(
ConfigDB.post(`/saved_query`, {
query,
...params
})
);

export const updateSavedQuery = (id: string, params: any) =>
resolve(ConfigDB.patch(`/saved_query?id=eq.${id}`, { ...params }));
resolvePostGrestRequestWithPagination(
ConfigDB.patch(`/saved_query?id=eq.${id}`, { ...params })
);

export const deleteSavedQuery = (id: string) =>
resolve(ConfigDB.delete(`/saved_query?id=eq.${id}`));
resolvePostGrestRequestWithPagination(
ConfigDB.delete(`/saved_query?id=eq.${id}`)
);

export const getConfigsByQuery = async (query: string) => {
const { data, error } = await resolve<{ results: { tags: any }[] }>(
Config.get(`/query?query=${query}`)
);
const { data, error } = await resolvePostGrestRequestWithPagination<{
results: { tags: any }[];
}>(Config.get(`/query?query=${query}`));
if (error) {
console.error(error);
return [];
Expand Down Expand Up @@ -618,7 +634,7 @@ export const getConfigInsights = (
pageIndex! * pageSize
}`;
}
return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<
Pick<
ConfigAnalysis,
Expand Down Expand Up @@ -667,7 +683,7 @@ export const getTopologyRelatedInsights = async (
}`;
}

return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<
| {
analysis_id: string;
Expand Down Expand Up @@ -749,7 +765,7 @@ export const getAllConfigInsights = async (
: // default sort by first_observed
"&order=first_observed.desc";

return resolve(
return resolvePostGrestRequestWithPagination(
ConfigDB.get<ConfigAnalysis[] | null>(
`/config_analysis_items?select=id,analysis_type,analyzer,severity,status,first_observed,last_observed,config:configs(id,name,config_class,type)${pagingParams}${queryParamsString}${sortString}`,
{
Expand Down
18 changes: 12 additions & 6 deletions src/api/services/evidence.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { IncidentCommander } from "../axios";
import { resolve } from "../resolve";
import { resolvePostGrestRequestWithPagination } from "../resolve";
import { Evidence } from "../types/evidence";

export const getEvidence = async (id: string) =>
resolve(IncidentCommander.get(`/evidences?id=eq.${id}`));
resolvePostGrestRequestWithPagination(
IncidentCommander.get(`/evidences?id=eq.${id}`)
);

export const createEvidence = async (
args: Omit<Evidence, "created_by" | "created_at" | "hypothesis_id" | "id">
Expand All @@ -25,7 +27,7 @@ export const createEvidence = async (
script
} = args;

return resolve(
return resolvePostGrestRequestWithPagination(
IncidentCommander.post<Evidence[]>(`/evidences`, {
config_id,
config_analysis_id,
Expand All @@ -46,14 +48,16 @@ export const createEvidence = async (
};

export const updateEvidence = async (id: string, params: Partial<Evidence>) =>
resolve(
resolvePostGrestRequestWithPagination(
IncidentCommander.patch<Evidence[] | null>(`/evidences?id=eq.${id}`, {
...params
})
);

export const deleteEvidence = async (id: string) =>
resolve(IncidentCommander.delete(`/evidences?id=eq.${id}`));
resolvePostGrestRequestWithPagination(
IncidentCommander.delete(`/evidences?id=eq.${id}`)
);

export const deleteEvidenceBulk = async (idList: string[]) => {
let ids = "";
Expand All @@ -63,5 +67,7 @@ export const deleteEvidenceBulk = async (idList: string[]) => {
ids += ",";
}
});
return resolve(IncidentCommander.delete(`/evidences?id=in.(${ids})`));
return resolvePostGrestRequestWithPagination(
IncidentCommander.delete(`/evidences?id=in.(${ids})`)
);
};
Loading

0 comments on commit c415667

Please sign in to comment.