Skip to content

Commit

Permalink
fix: camelToSnake to respect uppercase words, such as "GetAPIValue" -…
Browse files Browse the repository at this point in the history
…> "GET_API_VALUE" (#1046)

## Problem
`camelToSnake()` is converting the example string "TestAPI" ->
"TEST_AP_I" when converting a 3rd party integration proto files that I
am attempting to generate with the Nest option. I believe that the
conversion should respect the "API" part of the string and not split it
into two parts like so.

## Fix
I swapped the logic to use the already imported "case-anything"
library's `snakeCase()` function as `snakeCaseAnything()` and added a
couple of simple tests to ensure the logic.

I would love for this fix to go through as it is a pretty inconvenient
problem at the moment (:

Thanks!
  • Loading branch information
BrandonArmand authored May 25, 2024
1 parent 159c984 commit d2e75cd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/case.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { camelCase as camelCaseAnything } from "case-anything";
import { camelCase as camelCaseAnything, snakeCase as snakeCaseAnything } from "case-anything";

import { Options } from "./options";

Expand All @@ -24,7 +24,7 @@ export function snakeToCamel(s: string): string {
}

export function camelToSnake(s: string): string {
return s.replace(/\w([A-Z])/g, (m) => m[0] + "_" + m[1]).toUpperCase();
return snakeCaseAnything(s).toUpperCase();
}

export function capitalize(s: string): string {
Expand Down
10 changes: 9 additions & 1 deletion tests/case-test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { maybeSnakeToCamel, camelCaseGrpc } from "../src/case";
import { maybeSnakeToCamel, camelCaseGrpc, camelToSnake } from "../src/case";
import { Options, optionsFromParameter } from "../src/options";
import { getFieldJsonName } from "../src/utils";

Expand Down Expand Up @@ -51,6 +51,14 @@ describe("case", () => {
expect(camelCaseGrpc("GetAPIValue")).toEqual("getApiValue");
});

it("converts simple string to snake case, getApiValue === GET_API_VALUE", () => {
expect(camelToSnake("GetApiValue")).toEqual("GET_API_VALUE");
});

it("converts string to snake case respecting word separation, getAPIValue === GET_API_VALUE", () => {
expect(camelToSnake("getAPIValue")).toEqual("GET_API_VALUE");
});

describe("getFieldJsonName", () => {
it("keeps snake case when jsonName is probably not set", () => {
expect(getFieldJsonName({ name: "foo_bar", jsonName: "fooBar" }, { snakeToCamel: [], useJsonName: false })).toBe(
Expand Down

0 comments on commit d2e75cd

Please sign in to comment.