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
5 changes: 5 additions & 0 deletions .changeset/bruno-opencollection-format.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@labdigital/graphql-codegen-bruno": minor
---

Add the `format` option: `yml` writes the requests in the OpenCollection (YAML) format, for a Bruno collection with an `opencollection.yml`, which does not load `.bru` files. The default stays `bru`. `clean` now also removes previously generated `.yml` requests (except `folder.yml`).
3 changes: 2 additions & 1 deletion packages/bruno/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,12 @@ environment, or set `url` to match your environment variables.

| Option | Type | Default | Description |
| ------ | ---- | ------- | ----------- |
| `clean` | `boolean` | `false` | Remove the previously generated requests before generating: the `.bru` files in the `queries/`, `mutations/` and `subscriptions/` folders of the output directory (except `folder.bru`), and those folders when they are empty afterwards. Other files, such as `bruno.json`, `collection.bru` or environments, are never removed. |
| `clean` | `boolean` | `false` | Remove the previously generated requests before generating: the `.bru` and `.yml` files in the `queries/`, `mutations/` and `subscriptions/` folders of the output directory (except `folder.bru` and `folder.yml`), and those folders when they are empty afterwards. Other files, such as `bruno.json`, `collection.bru` or environments, are never removed. |
| `url` | `string` | `"{{graphql-gateway}}/graphql"` | URL of every request. May use Bruno variables. |
| `auth` | `string` | `"none"` | Auth mode of every request. Use `inherit` to use the auth configured on the collection or folder. |
| `headers` | `Record<string, string>` | `{}` | Headers added to the `headers` block of every request. Values may use Bruno variables, such as `{{token}}`. |
| `defaults` | `Record<string, unknown>` | `{}` | Values for operation variables, by variable name. A default replaces the generated example value of a top-level variable with the same name; variables that the operation does not declare are ignored. |
| `format` | `"bru" \| "yml"` | `"bru"` | File format of the requests. Use `yml` for a collection in the OpenCollection format (an `opencollection.yml` in its root), which does not load `.bru` files. `clean` removes generated requests of both formats, so switching format leaves no old requests behind. |

## Example output

Expand Down
3 changes: 2 additions & 1 deletion packages/bruno/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"publint": "^0.3.25",
"tsdown": "^0.23.1",
"typescript": "^7.0.2",
"vitest": "5.0.3"
"vitest": "5.0.3",
"yaml": "2.9.1"
},
"peerDependencies": {
"graphql": "^16.0.0 || ^17.0.0"
Expand Down
34 changes: 34 additions & 0 deletions packages/bruno/src/__snapshots__/yml/mutations/UpdateCustomer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
info:
name: "UpdateCustomer"
type: graphql
seq: 1

graphql:
method: POST
url: "{{graphql-gateway}}/graphql"
body:
query: |-
mutation UpdateCustomer($id: ID!, $firstName: String) {
updateCustomer(id: $id, firstName: $firstName) {
id
...CustomerDetails
}
}

fragment CustomerDetails on Customer {
firstName
email
addresses {
...AddressDetails
}
}

fragment AddressDetails on Address {
id
city
}
variables: |-
{
"id": "example-id",
"firstName": "example"
}
38 changes: 38 additions & 0 deletions packages/bruno/src/__snapshots__/yml/queries/GetCustomer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
info:
name: "GetCustomer"
type: graphql
seq: 1

graphql:
method: POST
url: "{{graphql-gateway}}/graphql"
body:
query: |-
query GetCustomer($info: CustomerInfo!) {
customer(info: $info) {
...CustomerDetails
}
}

fragment CustomerDetails on Customer {
firstName
email
addresses {
...AddressDetails
}
}

fragment AddressDetails on Address {
id
city
}
variables: |-
{
"info": {
"credentials": {
"email": "example",
"password": "example"
},
"authMethod": "EMAIL"
}
}
25 changes: 25 additions & 0 deletions packages/bruno/src/__snapshots__/yml/queries/GetProduct.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
info:
name: "GetProduct"
type: graphql
seq: 2

graphql:
method: POST
url: "{{graphql-gateway}}/graphql"
body:
query: |-
query GetProduct($id: ID!) {
product(id: $id) {
...ProductFields
}
}

fragment ProductFields on Product {
id
name
price
}
variables: |-
{
"id": "example-id"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
info:
name: "CustomerUpdated"
type: graphql
seq: 1

graphql:
method: POST
url: "{{graphql-gateway}}/graphql"
body:
query: |-
subscription CustomerUpdated($id: ID!) {
customerUpdated(id: $id) {
id
... on Customer {
...CustomerDetails
}
}
}

fragment CustomerDetails on Customer {
firstName
email
addresses {
...AddressDetails
}
}

fragment AddressDetails on Address {
id
city
}
variables: |-
{
"id": "example-id"
}
7 changes: 6 additions & 1 deletion packages/bruno/src/bruno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export interface BrunoPluginConfig {
* collection. Defaults to `none`.
*/
auth?: string;
/**
* File format of the requests: `bru` for a collection with a `bruno.json`,
* `yml` for a collection with an `opencollection.yml`. Defaults to `bru`.
*/
format?: "bru" | "yml";
}

export const asBruno = (
Expand Down Expand Up @@ -56,7 +61,7 @@ export const asBruno = (
return file.toString();
};

const mergeDefaults = (
export const mergeDefaults = (
vars: Record<string, unknown>,
defaults: Record<string, unknown>,
) => {
Expand Down
94 changes: 94 additions & 0 deletions packages/bruno/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Types } from "@graphql-codegen/plugin-helpers";
import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
import { loadDocumentsSync, loadSchemaSync } from "@graphql-tools/load";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { parse as parseYaml } from "yaml";
import type { BrunoPluginConfig } from "./bruno";
import { plugin } from "./index";

Expand Down Expand Up @@ -152,7 +153,100 @@ describe("Bruno Plugin", () => {
expect(getProduct).toContain('"id": "product-1"');
});

describe("format: yml", () => {
const ymlConfig: BrunoPluginConfig = { ...defaultConfig, format: "yml" };

it("writes OpenCollection requests", async () => {
const data = await plugin(schema, documents, ymlConfig, { outputFile });

expect(JSON.parse(data as string).GetProduct.filename).toBe(
"GetProduct.yml",
);
expect(listFiles(outputDir)).toEqual([
path.join("mutations", "UpdateCustomer.yml"),
path.join("queries", "GetCustomer.yml"),
path.join("queries", "GetProduct.yml"),
path.join("subscriptions", "CustomerUpdated.yml"),
]);
for (const file of listFiles(outputDir)) {
await expect(read(file)).toMatchFileSnapshot(
path.join(snapshotDir, "yml", file),
);
}
});

it("parses to the operation, its fragments and variables", async () => {
await plugin(
schema,
documents,
{
...ymlConfig,
url: "{{baseUrl}}/api/graphql",
auth: "inherit",
headers: { Authorization: "Bearer {{token}}", "X-Note": 'a: "b"' },
defaults: { id: "product-1" },
},
{ outputFile },
);

const request = parseYaml(read(path.join("queries", "GetProduct.yml")));
expect(request.info).toEqual({
name: "GetProduct",
type: "graphql",
seq: 2,
});
expect(request.graphql.url).toBe("{{baseUrl}}/api/graphql");
expect(request.graphql.auth).toBe("inherit");
expect(request.graphql.headers).toEqual([
{ name: "Authorization", value: "Bearer {{token}}" },
{ name: "X-Note", value: 'a: "b"' },
]);
expect(request.graphql.body.query).toContain("query GetProduct");
expect(request.graphql.body.query).toContain("fragment ProductFields");
expect(JSON.parse(request.graphql.body.variables)).toEqual({
id: "product-1",
});
});

it("leaves auth out for none, and writes another mode as its type", async () => {
await plugin(schema, documents, ymlConfig, { outputFile });
const none = parseYaml(read(path.join("queries", "GetProduct.yml")));
expect(none.graphql.auth).toBeUndefined();

await plugin(
schema,
documents,
{ ...ymlConfig, auth: "bearer" },
{ outputFile },
);
const bearer = parseYaml(read(path.join("queries", "GetProduct.yml")));
expect(bearer.graphql.auth).toEqual({ type: "bearer" });
});
});

describe("clean", () => {
it("removes requests generated in the other format", async () => {
const writeFile = (file: string) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, "");
};
writeFile(path.join(outputDir, "queries", "Removed.yml"));
writeFile(path.join(outputDir, "queries", "folder.yml"));

await plugin(
schema,
documents,
{ ...defaultConfig, clean: true },
{ outputFile },
);

expect(listFiles(path.join(outputDir, "queries"))).toEqual([
"GetCustomer.bru",
"GetProduct.bru",
"folder.yml",
]);
});

const writeFile = (file: string, content = "") => {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
Expand Down
29 changes: 21 additions & 8 deletions packages/bruno/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from "node:path";
import type { PluginFunction, Types } from "@graphql-codegen/plugin-helpers";
import type { GraphQLSchema, OperationTypeNode } from "graphql";
import { asBruno, type BrunoPluginConfig } from "./bruno";
import { asOpenCollection } from "./opencollection";
import { extractOperations } from "./operations";

export const plugin: PluginFunction<BrunoPluginConfig> = async (
Expand All @@ -22,16 +23,25 @@ export const plugin: PluginFunction<BrunoPluginConfig> = async (
const operations = extractOperations(schema, documents).sort((a, b) =>
a.name.localeCompare(b.name),
);
const format = config.format ?? "bru";
const seqs: Partial<Record<OperationTypeNode, number>> = {};
const result: Record<string, Record<string, string>> = {};
for (const operation of operations) {
const fileName = `${operation.name}.bru`;
const fileName = `${operation.name}.${format}`;
const outputPath = path.join(
outputDir,
OPERATION_FOLDERS[operation.kind],
fileName,
);
const seq = (seqs[operation.kind] ?? 0) + 1;
seqs[operation.kind] = seq;

outputFileSync(outputPath, asBruno(operation, config));
outputFileSync(
outputPath,
format === "yml"
? asOpenCollection(operation, config, seq)
: asBruno(operation, config),
);
result[operation.name] = {
filename: fileName,
source: operation.location
Expand All @@ -49,11 +59,14 @@ const OPERATION_FOLDERS: Record<OperationTypeNode, string> = {
subscription: "subscriptions",
};

const GENERATED_EXTENSIONS = new Set([".bru", ".yml"]);
const FOLDER_SETTINGS = new Set(["folder.bru", "folder.yml"]);

/**
* Removes the requests generated by a previous run: the `.bru` files in the
* folders this plugin writes to, and those folders when they are empty
* afterwards. Other files, such as `bruno.json`, environments or a
* `folder.bru` with folder settings, are kept.
* Removes the requests generated by a previous run, in either format: the
* `.bru` and `.yml` files in the folders this plugin writes to, and those
* folders when they are empty afterwards. Other files, such as `bruno.json`,
* environments or a `folder.bru`/`folder.yml` with folder settings, are kept.
*/
function cleanGeneratedFiles(outputDir: string): void {
for (const folder of Object.values(OPERATION_FOLDERS)) {
Expand All @@ -64,8 +77,8 @@ function cleanGeneratedFiles(outputDir: string): void {
for (const entry of nodeFs.readdirSync(dirPath, { withFileTypes: true })) {
if (
entry.isFile() &&
entry.name.endsWith(".bru") &&
entry.name !== "folder.bru"
GENERATED_EXTENSIONS.has(path.extname(entry.name)) &&
!FOLDER_SETTINGS.has(entry.name)
) {
nodeFs.rmSync(path.join(dirPath, entry.name));
}
Expand Down
Loading