-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathatlassian.api.controller.ts
More file actions
203 lines (180 loc) · 5.47 KB
/
atlassian.api.controller.ts
File metadata and controls
203 lines (180 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import {
fetchAtlassian,
getAtlassianCredentials,
} from '../utils/transport.util.js';
import { Logger } from '../utils/logger.util.js';
import { handleControllerError } from '../utils/error-handler.util.js';
import { ControllerResponse } from '../types/common.types.js';
import {
GetApiToolArgsType,
RequestWithBodyArgsType,
} from '../tools/atlassian.api.types.js';
import { applyJqFilter, toOutputString } from '../utils/jq.util.js';
import { createAuthMissingError } from '../utils/error.util.js';
// Logger instance for this module
const logger = Logger.forContext('controllers/atlassian.api.controller.ts');
/**
* Supported HTTP methods for API requests
*/
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
/**
* Output format type
*/
type OutputFormat = 'toon' | 'json';
/**
* Base options for all API requests
*/
interface BaseRequestOptions {
path: string;
queryParams?: Record<string, string>;
jq?: string;
outputFormat?: OutputFormat;
}
/**
* Options for requests that include a body (POST, PUT, PATCH)
*/
interface RequestWithBodyOptions extends BaseRequestOptions {
body?: Record<string, unknown>;
}
/**
* Normalizes the API path by ensuring it starts with /
* @param path - The raw path provided by the user
* @returns Normalized path
*/
function normalizePath(path: string): string {
let normalizedPath = path;
if (!normalizedPath.startsWith('/')) {
normalizedPath = '/' + normalizedPath;
}
return normalizedPath;
}
/**
* Appends query parameters to a path
* @param path - The base path
* @param queryParams - Optional query parameters
* @returns Path with query string appended
*/
function appendQueryParams(
path: string,
queryParams?: Record<string, string>,
): string {
if (!queryParams || Object.keys(queryParams).length === 0) {
return path;
}
const queryString = new URLSearchParams(queryParams).toString();
return path + (path.includes('?') ? '&' : '?') + queryString;
}
/**
* Shared handler for all HTTP methods
*
* @param method - HTTP method (GET, POST, PUT, PATCH, DELETE)
* @param options - Request options including path, queryParams, body (for non-GET), and jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
async function handleRequest(
method: HttpMethod,
options: RequestWithBodyOptions,
): Promise<ControllerResponse> {
const methodLogger = logger.forMethod(`handle${method}`);
try {
methodLogger.debug(`Making ${method} request`, {
path: options.path,
...(options.body && { bodyKeys: Object.keys(options.body) }),
});
// Get credentials
const credentials = getAtlassianCredentials();
if (!credentials) {
throw createAuthMissingError();
}
// Normalize path and append query params
let path = normalizePath(options.path);
path = appendQueryParams(path, options.queryParams);
methodLogger.debug(`${method}ing: ${path}`);
const fetchOptions: {
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
} = {
method,
};
// Add body for methods that support it
if (options.body && ['POST', 'PUT', 'PATCH'].includes(method)) {
fetchOptions.body = options.body;
}
const response = await fetchAtlassian<unknown>(
credentials,
path,
fetchOptions,
);
methodLogger.debug('Successfully received response');
// Apply JQ filter if provided, otherwise return raw data
const result = applyJqFilter(response, options.jq);
// Convert to output format (TOON by default, JSON if requested)
const useToon = options.outputFormat !== 'json';
const content = await toOutputString(result, useToon);
return {
content,
};
} catch (error) {
throw handleControllerError(error, {
entityType: 'API',
operation: `${method} request`,
source: `controllers/atlassian.api.controller.ts@handle${method}`,
additionalInfo: { path: options.path },
});
}
}
/**
* Generic GET request to Confluence API
*
* @param options - Options containing path, queryParams, and optional jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
export async function handleGet(
options: GetApiToolArgsType,
): Promise<ControllerResponse> {
return handleRequest('GET', options);
}
/**
* Generic POST request to Confluence API
*
* @param options - Options containing path, body, queryParams, and optional jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
export async function handlePost(
options: RequestWithBodyArgsType,
): Promise<ControllerResponse> {
return handleRequest('POST', options);
}
/**
* Generic PUT request to Confluence API
*
* @param options - Options containing path, body, queryParams, and optional jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
export async function handlePut(
options: RequestWithBodyArgsType,
): Promise<ControllerResponse> {
return handleRequest('PUT', options);
}
/**
* Generic PATCH request to Confluence API
*
* @param options - Options containing path, body, queryParams, and optional jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
export async function handlePatch(
options: RequestWithBodyArgsType,
): Promise<ControllerResponse> {
return handleRequest('PATCH', options);
}
/**
* Generic DELETE request to Confluence API
*
* @param options - Options containing path, queryParams, and optional jq filter
* @returns Promise with raw JSON response (optionally filtered)
*/
export async function handleDelete(
options: GetApiToolArgsType,
): Promise<ControllerResponse> {
return handleRequest('DELETE', options);
}