-
Notifications
You must be signed in to change notification settings - Fork 85
chore: auto generate apiClient #64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
949f718
chore: auto generate apiClient
fmenezes 6b183f2
fix vscode settings
fmenezes fd473f5
chore: drive-by
fmenezes 284f660
fix: styles
fmenezes 96704b8
fix: promises
fmenezes 365f457
fix: default paramenter
fmenezes 89dc471
Merge branch 'main' into fmenezes/autoGenerateApiClient
fmenezes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import fs, { writeFile } from "fs"; | ||
import { OpenAPIV3_1 } from "openapi-types"; | ||
import argv from "yargs-parser"; | ||
import { promisify } from "util"; | ||
|
||
const readFileAsync = promisify(fs.readFile); | ||
const writeFileAsync = promisify(fs.writeFile); | ||
|
||
function findParamFromRef(ref: string, openapi: OpenAPIV3_1.Document): OpenAPIV3_1.ParameterObject { | ||
const paramParts = ref.split("/"); | ||
paramParts.shift(); // Remove the first part which is always '#' | ||
let param: any = openapi; // eslint-disable-line @typescript-eslint/no-explicit-any | ||
while (true) { | ||
const part = paramParts.shift(); | ||
if (!part) { | ||
break; | ||
} | ||
param = param[part]; | ||
} | ||
return param; | ||
} | ||
|
||
async function main() { | ||
const {spec, file} = argv(process.argv.slice(2)); | ||
|
||
if (!spec || !file) { | ||
console.error("Please provide both --spec and --file arguments."); | ||
process.exit(1); | ||
} | ||
|
||
const specFile = await readFileAsync(spec, "utf8") as string; | ||
|
||
const operations: { | ||
path: string; | ||
method: string; | ||
operationId: string; | ||
requiredParams: boolean; | ||
tag: string; | ||
}[] = []; | ||
|
||
const openapi = JSON.parse(specFile) as OpenAPIV3_1.Document; | ||
for (const path in openapi.paths) { | ||
for (const method in openapi.paths[path]) { | ||
const operation: OpenAPIV3_1.OperationObject = openapi.paths[path][method]; | ||
|
||
if (!operation.operationId || !operation.tags?.length) { | ||
continue; | ||
} | ||
|
||
let requiredParams = !!operation.requestBody; | ||
|
||
for (const param of operation.parameters || []) { | ||
const ref = (param as OpenAPIV3_1.ReferenceObject).$ref as string | undefined; | ||
let paramObject: OpenAPIV3_1.ParameterObject = param as OpenAPIV3_1.ParameterObject; | ||
if (ref) { | ||
paramObject = findParamFromRef(ref, openapi); | ||
} | ||
if (paramObject.in === "path") { | ||
requiredParams = true; | ||
} | ||
} | ||
|
||
operations.push({ | ||
path, | ||
method: method.toUpperCase(), | ||
operationId: operation.operationId || '', | ||
requiredParams, | ||
tag: operation.tags[0], | ||
}); | ||
} | ||
} | ||
|
||
const operationOutput = operations.map((operation) => { | ||
const { operationId, method, path, requiredParams } = operation; | ||
return `async ${operationId}(options${requiredParams ? '' : '?'}: FetchOptions<operations["${operationId}"]>) { | ||
const { data } = await this.client.${method}("${path}", options); | ||
return data; | ||
} | ||
`; | ||
}).join("\n"); | ||
|
||
const templateFile = await readFileAsync(file, "utf8") as string; | ||
const output = templateFile.replace(/\/\/ DO NOT EDIT\. This is auto-generated code\.\n.*\/\/ DO NOT EDIT\. This is auto-generated code\./g, operationOutput); | ||
|
||
await writeFileAsync(file, output, "utf8"); | ||
} | ||
|
||
main().catch((error) => { | ||
console.error("Error:", error); | ||
process.exit(1); | ||
}); |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
export class ApiClientError extends Error { | ||
response?: Response; | ||
|
||
constructor(message: string, response: Response | undefined = undefined) { | ||
super(message); | ||
this.name = "ApiClientError"; | ||
this.response = response; | ||
} | ||
|
||
static async fromResponse(response: Response, message?: string): Promise<ApiClientError> { | ||
message ||= `error calling Atlas API`; | ||
try { | ||
const text = await response.text(); | ||
return new ApiClientError(`${message}: [${response.status} ${response.statusText}] ${text}`, response); | ||
} catch { | ||
return new ApiClientError(`${message}: ${response.status} ${response.statusText}`, response); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ import config from "./config.js"; | |
import redact from "mongodb-redact"; | ||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; | ||
import { LoggingMessageNotification } from "@modelcontextprotocol/sdk/types.js"; | ||
import { promisify } from "util"; | ||
|
||
export type LogLevel = LoggingMessageNotification["params"]["level"]; | ||
|
||
|
@@ -98,20 +99,10 @@ class ProxyingLogger extends LoggerBase { | |
const logger = new ProxyingLogger(); | ||
export default logger; | ||
|
||
async function mkdirPromise(path: fs.PathLike, options?: fs.Mode | fs.MakeDirectoryOptions) { | ||
return new Promise<string | undefined>((resolve, reject) => { | ||
fs.mkdir(path, options, (err, resultPath) => { | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve(resultPath); | ||
} | ||
}); | ||
}); | ||
} | ||
const mkdirAsync = promisify(fs.mkdir); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here with |
||
|
||
export async function initializeLogger(server: McpServer): Promise<void> { | ||
await mkdirPromise(config.logPath, { recursive: true }); | ||
await mkdirAsync(config.logPath, { recursive: true }); | ||
|
||
const manager = new MongoLogManager({ | ||
directory: config.logPath, | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.