Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion moon/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,6 @@ dump.rdb

# PostHog migrations and backups
posthog_migration
posthog_migration_batches
posthog_migration_batches

api/gen
59 changes: 59 additions & 0 deletions moon/api/merge-swagger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");

const fileBase = path.join(process.cwd(), "api/gen");
const outputFile = path.join(fileBase, "merged_swagger.json");

// 要排除的文件
const excludeFiles = new Set([
"merged_swagger.json",
"openapi_schema.json",
]);

// 找到所有 JSON 文件,排除指定的文件
const files = fs
.readdirSync(fileBase)
.filter((f) => f.endsWith(".json") && !excludeFiles.has(f))
.map((f) => path.join(fileBase, f));

if (files.length === 0) {
console.error("没有找到 JSON 文件可供合并");
process.exit(1);
}

// 深度合并函数
function deepMerge(target, source) {
for (const key of Object.keys(source)) {
if (
typeof target[key] === "object" &&
target[key] !== null &&
!Array.isArray(target[key]) &&
typeof source[key] === "object" &&
source[key] !== null &&
!Array.isArray(source[key])
) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}

// 依次读取并 merge
const merged = files
.map((file) => JSON.parse(fs.readFileSync(file, "utf-8")))
.reduce(
(acc, swagger) => {
acc.info = acc.info && Object.keys(acc.info).length > 0 ? acc.info : swagger.info || {};
acc.paths = { ...acc.paths, ...(swagger.paths || {}) };
acc.components = deepMerge(acc.components, swagger.components || {});
return acc;
},
{ openapi: "3.0.0", info: {}, paths: {}, components: {} }
);

// 输出文件
fs.writeFileSync(outputFile, JSON.stringify(merged, null, 2));
console.log(`Swagger JSON 文件合并完成,已生成 ${outputFile} 🎉`);
12 changes: 10 additions & 2 deletions moon/packages/types/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4989,6 +4989,13 @@ export type GetApiMrMergeBoxData = CommonResultMergeBoxRes

export type PostApiMrMergeNoAuthData = CommonResultString

export type GetApiMrMuiTreeParams = {
oid?: string | null
path?: string
/** MR link */
link: string
}

export type GetApiMrMuiTreeData = CommonResultVecMuiTreeNode

export type DeleteApiMrRemoveReviewersData = CommonResultString
Expand Down Expand Up @@ -14272,11 +14279,12 @@ It's for local testing purposes.

return {
baseKey: dataTaggedQueryKey<GetApiMrMuiTreeData>([base]),
requestKey: (link: string) => dataTaggedQueryKey<GetApiMrMuiTreeData>([base, link]),
request: (link: string, params: RequestParams = {}) =>
requestKey: (params: GetApiMrMuiTreeParams) => dataTaggedQueryKey<GetApiMrMuiTreeData>([base, params]),
request: ({ link, ...query }: GetApiMrMuiTreeParams, params: RequestParams = {}) =>
this.request<GetApiMrMuiTreeData>({
path: `/api/v1/mr/${link}/mui-tree`,
method: 'GET',
query: query,
...params
})
}
Expand Down
36 changes: 36 additions & 0 deletions moon/script/gen-client
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/bin/bash

set -eou pipefail

OPENAPI_FILE_PATH=api/gen/openapi_schema.json
SWAGGER_FILE_PATH=api/gen/merged_swagger.json

# swagger-typescript-api does not work with ES Modules which is required for our prettier v3 plugins
# and swagger-typescript-api automatically detects and runs prettier on generated files
mv .prettierrc.json .prettierrc_temp.json

# (cd api && bundle exec rake apigen:merge_swagger)

OUT=./gen node api/merge-swagger.js

# generate client types
pnpm swagger-typescript-api \
--extract-request-params \
--extract-request-body \
--extract-response-body \
--extract-response-error \
--module-name-index 1 \
--module-name-first-tag true \
--templates script/swagger-templates \
--path $SWAGGER_FILE_PATH \
--output ./packages/types/ \
--name generated.ts

# remove swagger docs so we only check in the generated client types
# rm $SWAGGER_FILE_PATH

# Put .prettierrc.json back
mv .prettierrc_temp.json .prettierrc.json

# format generated files
pnpm prettier --config .prettierrc.json --write ./packages/types/generated.ts ./$OPENAPI_FILE_PATH
80 changes: 80 additions & 0 deletions moon/script/swagger-templates/api.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<%
const { apiConfig, routes, utils, config } = it;
const { info, servers, externalDocs } = apiConfig;
const { _, require, formatDescription } = utils;

const server = (servers && servers[0]) || { url: "" };

const descriptionLines = _.compact([
`@title ${info.title || "No title"}`,
info.version && `@version ${info.version}`,
info.license && `@license ${_.compact([
info.license.name,
info.license.url && `(${info.license.url})`,
]).join(" ")}`,
info.termsOfService && `@termsOfService ${info.termsOfService}`,
server.url && `@baseUrl ${server.url}`,
externalDocs.url && `@externalDocs ${externalDocs.url}`,
info.contact && `@contact ${_.compact([
info.contact.name,
info.contact.email && `<${info.contact.email}>`,
info.contact.url && `(${info.contact.url})`,
]).join(" ")}`,
info.description && " ",
info.description && _.replace(formatDescription(info.description), /\n/g, "\n * "),
]);

%>

declare const dataTagSymbol: unique symbol

export type DataTag<Type, Value> = Type & {
[dataTagSymbol]: Value
}

function dataTaggedQueryKey<TData, TKey extends readonly unknown[] = unknown[]>(key: TKey): TKey & DataTag<TKey, TData>
function dataTaggedQueryKey(key: unknown) {
return key
}

<% if (config.httpClientType === config.constants.HTTP_CLIENT.AXIOS) { %> import type { AxiosRequestConfig, AxiosResponse } from "axios"; <% } %>

<% if (descriptionLines.length) { %>
/**
<% descriptionLines.forEach((descriptionLine) => { %>
* <%~ descriptionLine %>

<% }) %>
*/
<% } %>
export class <%~ config.apiClassName %><SecurityDataType extends unknown><% if (!config.singleHttpClient) { %> extends HttpClient<SecurityDataType> <% } %> {

<% if(config.singleHttpClient) { %>
http: HttpClient<SecurityDataType>;

constructor (http: HttpClient<SecurityDataType>) {
this.http = http;
}
<% } %>


<% if (routes.outOfModule) { %>
<% for (const route of routes.outOfModule) { %>

<%~ includeFile('./keyed-procedure-call.ejs', { ...it, route }) %>

<% } %>
<% } %>

<% if (routes.combined) { %>
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
<%~ moduleName %> = {
<% for (const route of combinedRoutes) { %>

<%~ includeFile('./keyed-procedure-call.ejs', { ...it, route }) %>

<% } %>
}
<% } %>
<% } %>
}
41 changes: 41 additions & 0 deletions moon/script/swagger-templates/data-contracts.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<%
const { modelTypes, utils, config } = it;
const { formatDescription, require, _, Ts } = utils;


const buildGenerics = (contract) => {
if (!contract.genericArgs || !contract.genericArgs.length) return '';

return '<' + contract.genericArgs.map(({ name, default: defaultType, extends: extendsType }) => {
return [
name,
extendsType && `extends ${extendsType}`,
defaultType && `= ${defaultType}`,
].join('')
}).join(',') + '>'
}

const dataContractTemplates = {
enum: (contract) => {
return `enum ${contract.name} {\r\n${contract.content} \r\n }`;
},
// Force all interfaces to type
interface: (contract) => {
return `type ${contract.name} = {\r\n ${contract.content} \r\n}`;
},
type: (contract) => {
return `type ${contract.name}${buildGenerics(contract)} = ${contract.content}`;
},
}
%>

<% if (config.internalTemplateOptions.addUtilRequiredKeysType) { %>
type <%~ config.Ts.CodeGenKeyword.UtilRequiredKeys %><T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
<% } %>

<% for (const contract of modelTypes) { %>
<%~ includeFile('@base/data-contract-jsdoc.ejs', { ...it, data: { ...contract, ...contract.typeData } }) %>
<%~ contract.internal ? '' : 'export'%> <%~ (dataContractTemplates[contract.typeIdentifier] || dataContractTemplates.type)(contract) %>


<% } %>
Loading
Loading