Skip to content
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

Style: Single statement blocks and empty returns #2156

Merged
merged 15 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 2 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export default [
{
name: "globally/enabled",
rules: {
curly: ["warn", "multi-or-nest", "consistent"],
"unicorn/prefer-node-protocol": "error",
// "no-restricted-syntax": ["warn", "ReturnStatement[argument=null]"],
},
},
{
Expand Down
26 changes: 6 additions & 20 deletions example/factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,10 @@ export const fileSendingEndpointsFactory = new EndpointsFactory({
positive: { schema: z.string(), mimeType: "image/svg+xml" },
negative: { schema: z.string(), mimeType: "text/plain" },
handler: ({ response, error, output }) => {
if (error) {
response.status(400).send(error.message);
return;
}
if (output && "data" in output && typeof output.data === "string") {
if (error) return void response.status(400).send(error.message);
if (output && "data" in output && typeof output.data === "string")
response.type("svg").send(output.data);
} else {
response.status(400).send("Data is missing");
}
else response.status(400).send("Data is missing");
},
}),
});
Expand All @@ -48,19 +43,10 @@ export const fileStreamingEndpointsFactory = new EndpointsFactory({
positive: { schema: ez.file("buffer"), mimeType: "image/*" },
negative: { schema: z.string(), mimeType: "text/plain" },
handler: ({ response, error, output }) => {
if (error) {
response.status(400).send(error.message);
return;
}
if (
output &&
"filename" in output &&
typeof output.filename === "string"
) {
if (error) return void response.status(400).send(error.message);
if (output && "filename" in output && typeof output.filename === "string")
createReadStream(output.filename).pipe(response.type(output.filename));
} else {
response.status(400).send("Filename is missing");
}
else response.status(400).send("Filename is missing");
},
}),
});
Expand Down
11 changes: 3 additions & 8 deletions src/common-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ export const getInput = (
userDefined: CommonConfig["inputSources"] = {},
): FlatObject => {
const method = getActualMethod(req);
if (method === "options") {
return {};
}
if (method === "options") return {};
return (
userDefined[method] ||
defaultInputSources[method] ||
Expand Down Expand Up @@ -95,15 +93,12 @@ export const getExamples = <
validate?: boolean;
}): ReadonlyArray<V extends "parsed" ? z.output<T> : z.input<T>> => {
const examples = schema._def[metaSymbol]?.examples || [];
if (!validate && variant === "original") {
return examples;
}
if (!validate && variant === "original") return examples;
const result: Array<z.input<T> | z.output<T>> = [];
for (const example of examples) {
const parsedExample = schema.safeParse(example);
if (parsedExample.success) {
if (parsedExample.success)
result.push(variant === "parsed" ? parsedExample.data : example);
}
}
return result;
};
Expand Down
99 changes: 30 additions & 69 deletions src/documentation-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,8 @@ const tryFlattenIntersection = (
right.properties || {},
);
}
if (left.required || right.required) {
if (left.required || right.required)
flat.required = union(left.required || [], right.required || []);
}
if (left.examples || right.examples) {
flat.examples = combinations(
left.examples || [],
Expand Down Expand Up @@ -244,9 +243,7 @@ export const depictNullable: Depicter = (
{ next },
) => {
const nested = next(schema.unwrap());
if (isSchemaObject(nested)) {
nested.type = makeNullableType(nested);
}
if (isSchemaObject(nested)) nested.type = makeNullableType(nested);
return nested;
};

Expand Down Expand Up @@ -289,12 +286,8 @@ export const depictObject: Depicter = (
: prop.isOptional();
const required = keys.filter((key) => !isOptionalProp(schema.shape[key]));
const result: SchemaObject = { type: "object" };
if (keys.length) {
result.properties = depictObjectProperties(schema, next);
}
if (required.length) {
result.required = required;
}
if (keys.length) result.properties = depictObjectProperties(schema, next);
if (required.length) result.required = required;
return result;
};

Expand Down Expand Up @@ -409,12 +402,8 @@ export const depictArray: Depicter = (
{ next },
) => {
const result: SchemaObject = { type: "array", items: next(element) };
if (minLength) {
result.minItems = minLength.value;
}
if (maxLength) {
result.maxItems = maxLength.value;
}
if (minLength) result.minItems = minLength.value;
if (maxLength) result.maxItems = maxLength.value;
return result;
};

Expand Down Expand Up @@ -475,15 +464,9 @@ export const depictString: Depicter = ({
break;
}
}
if (minLength !== null) {
result.minLength = minLength;
}
if (maxLength !== null) {
result.maxLength = maxLength;
}
if (regex) {
result.pattern = regex.source;
}
if (minLength !== null) result.minLength = minLength;
if (maxLength !== null) result.maxLength = maxLength;
if (regex) result.pattern = regex.source;
return result;
};

Expand Down Expand Up @@ -514,16 +497,10 @@ export const depictNumber: Depicter = ({
type: isInt ? "integer" : "number",
format: isInt ? "int64" : "double",
};
if (isMinInclusive) {
result.minimum = minimum;
} else {
result.exclusiveMinimum = minimum;
}
if (isMaxInclusive) {
result.maximum = maximum;
} else {
result.exclusiveMaximum = maximum;
}
if (isMinInclusive) result.minimum = minimum;
else result.exclusiveMinimum = minimum;
if (isMaxInclusive) result.maximum = maximum;
else result.exclusiveMaximum = maximum;
return result;
};

Expand All @@ -539,12 +516,12 @@ const makeSample = (depicted: SchemaObject) => {
return samples?.[firstType];
};

const makeNullableType = (prev: SchemaObject): SchemaObjectType[] => {
const current = typeof prev.type === "string" ? [prev.type] : prev.type || [];
if (current.includes("null")) {
return current;
}
return current.concat("null");
const makeNullableType = ({
type,
}: SchemaObject): SchemaObjectType | SchemaObjectType[] => {
if (type === "null") return type;
if (typeof type === "string") return [type, "null"];
return type ? [...new Set(type).add("null")] : "null";
};

export const depictEffect: Depicter = (
Expand All @@ -555,11 +532,9 @@ export const depictEffect: Depicter = (
const { effect } = schema._def;
if (isResponse && effect.type === "transform" && isSchemaObject(input)) {
const outputType = tryToTransform(schema, makeSample(input));
if (outputType && ["number", "string", "boolean"].includes(outputType)) {
if (outputType && ["number", "string", "boolean"].includes(outputType))
return { type: outputType as "number" | "string" | "boolean" };
} else {
return next(z.any());
}
else return next(z.any());
}
if (!isResponse && effect.type === "preprocess" && isSchemaObject(input)) {
const { type: inputType, ...rest } = input;
Expand Down Expand Up @@ -624,12 +599,9 @@ export const depictParamExamples = (
export const extractObjectSchema = (
subject: IOSchema,
): z.ZodObject<z.ZodRawShape> => {
if (subject instanceof z.ZodObject) {
return subject;
}
if (subject instanceof z.ZodBranded) {
if (subject instanceof z.ZodObject) return subject;
if (subject instanceof z.ZodBranded)
return extractObjectSchema(subject.unwrap());
}
if (
subject instanceof z.ZodUnion ||
subject instanceof z.ZodDiscriminatedUnion
Expand Down Expand Up @@ -790,19 +762,13 @@ export const excludeParamsFromDepiction = (
depicted: SchemaObject | ReferenceObject,
names: string[],
): SchemaObject | ReferenceObject => {
if (isReferenceObject(depicted)) {
return depicted;
}
if (isReferenceObject(depicted)) return depicted;
const copy = { ...depicted };
if (copy.properties) {
copy.properties = omit(names, copy.properties);
}
if (copy.examples) {
if (copy.properties) copy.properties = omit(names, copy.properties);
if (copy.examples)
copy.examples = copy.examples.map((entry) => omit(names, entry));
}
if (copy.required) {
if (copy.required)
copy.required = copy.required.filter((name) => !names.includes(name));
}
if (copy.allOf) {
copy.allOf = copy.allOf.map((entry) =>
excludeParamsFromDepiction(entry, names),
Expand Down Expand Up @@ -875,9 +841,7 @@ const depictBearerSecurity: SecurityHelper<"bearer"> = ({
type: "http",
scheme: "bearer",
};
if (bearerFormat) {
result.bearerFormat = bearerFormat;
}
if (bearerFormat) result.bearerFormat = bearerFormat;
return result;
};
const depictInputSecurity: SecurityHelper<"input"> = (
Expand Down Expand Up @@ -956,9 +920,7 @@ export const depictSecurityRefs = (
: { [entry.name]: entry.scopes },
);
}
if ("and" in container) {
return depictSecurityRefs(andToOr(container));
}
if ("and" in container) return depictSecurityRefs(andToOr(container));
return depictSecurityRefs({ or: [container] });
RobinTail marked this conversation as resolved.
Show resolved Hide resolved
};

Expand Down Expand Up @@ -1006,9 +968,8 @@ export const depictTags = <TAG extends string>(
name: tag,
description: typeof def === "string" ? def : def.description,
};
if (typeof def === "object" && def.url) {
if (typeof def === "object" && def.url)
result.externalDocs = { url: def.url };
}
return result;
});

Expand Down
6 changes: 2 additions & 4 deletions src/documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,8 @@ export class Documentation extends OpenApiBuilder {
if (
serializedSubject ===
JSON.stringify(this.rootDoc.components?.securitySchemes?.[name])
) {
)
return name;
}
}
const nextId = (this.lastSecuritySchemaIds.get(subject.type) || 0) + 1;
this.lastSecuritySchemaIds.set(subject.type, nextId);
Expand All @@ -150,9 +149,8 @@ export class Documentation extends OpenApiBuilder {
}: DocumentationParams) {
super();
this.addInfo({ title, version });
for (const url of typeof serverUrl === "string" ? [serverUrl] : serverUrl) {
for (const url of typeof serverUrl === "string" ? [serverUrl] : serverUrl)
RobinTail marked this conversation as resolved.
Show resolved Hide resolved
this.addServer({ url });
}
const onEndpoint: RoutingWalkerParams["onEndpoint"] = (
endpoint,
path,
Expand Down
20 changes: 5 additions & 15 deletions src/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,8 @@ export class Endpoint<
public override getSchema(variant: "output"): OUT;
public override getSchema(variant: ResponseVariant): z.ZodTypeAny;
public override getSchema(variant: IOVariant | ResponseVariant) {
if (variant === "input" || variant === "output") {
if (variant === "input" || variant === "output")
return this.#schemas[variant];
}
return this.getResponses(variant)
.map(({ schema }) => schema)
.reduce((agg, schema) => agg.or(schema));
Expand Down Expand Up @@ -228,9 +227,7 @@ export class Endpoint<
options: Partial<OPT>;
}) {
for (const mw of this.#middlewares) {
if (method === "options" && !(mw instanceof ExpressMiddleware)) {
continue;
}
if (method === "options" && !(mw instanceof ExpressMiddleware)) continue;
Object.assign(
options,
await mw.execute({ input, options, request, response, logger }),
Expand Down Expand Up @@ -332,9 +329,7 @@ export class Endpoint<
defaultHeaders: headers,
});
}
for (const key in headers) {
response.set(key, headers[key]);
}
for (const key in headers) response.set(key, headers[key]);
}
const input = getInput(request, config.inputSources);
try {
Expand All @@ -346,13 +341,8 @@ export class Endpoint<
logger,
options,
});
if (response.writableEnded) {
return;
}
if (method === "options") {
response.status(200).end();
return;
}
if (response.writableEnded) return;
if (method === "options") return void response.status(200).end();
output = await this.#parseOutput(
await this.#parseAndRunHandler({
input,
Expand Down
2 changes: 1 addition & 1 deletion src/graceful-shutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const monitor = (
? /* v8 ignore next -- unstable */ socket.destroy()
: sockets.add(socket.once("close", () => void sockets.delete(socket))));

for (const server of servers)
for (const server of servers) // eslint-disable-next-line curly
for (const event of ["connection", "secureConnection"])
server.on(event, watch);

Expand Down
10 changes: 3 additions & 7 deletions src/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,8 @@ export class Integration {
const propName = quoteProp(method, path);
// "get /v1/user/retrieve": GetV1UserRetrieveInput
for (const face of this.interfaces) {
if (face.kind in rest) {
if (face.kind in rest)
face.props.push(makeInterfaceProp(propName, rest[face.kind]!));
}
}
if (variant !== "types") {
if (isJson) {
Expand All @@ -308,13 +307,10 @@ export class Integration {
}

// export interface Input ___ { "get /v1/user/retrieve": GetV1UserRetrieveInput; }
for (const { id, props } of this.interfaces) {
for (const { id, props } of this.interfaces)
this.program.push(makePublicExtendedInterface(id, extenderClause, props));
}

if (variant === "types") {
return;
}
if (variant === "types") return;

// export const jsonEndpoints = { "get /v1/user/retrieve": true }
const jsonEndpointsConst = f.createVariableStatement(
Expand Down
Loading