Skip to content

Commit 242ba97

Browse files
Merge pull request #5 from radekBednarik/dev
Dev
2 parents 02b765f + 822a946 commit 242ba97

File tree

7 files changed

+153
-13
lines changed

7 files changed

+153
-13
lines changed

README.md

+30-9
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,17 @@ npx expectations -h
1919
Usage: expectations [options] [command]
2020

2121
Options:
22-
-V, --version output the version number
23-
-c, --config <path> set config path. defaults to './mockserver.config.json' (default: "./mockserver.config.json")
24-
--concurrency <number> set number of concurrent requests. defaults to '10' (default: "10")
25-
-h, --help display help for command
22+
-V, --version output the version number
23+
-c, --config <path> set config path. defaults to './mockserver.config.json' (default: "./mockserver.config.json")
24+
--concurrency <number> set number of concurrent requests. defaults to '10' (default: "10")
25+
-h, --help display help for command
2626

2727
Commands:
28-
set <paths...> send prepared expectations up to the mockserver instance
29-
clear <paths...> clear all expectations from the mockserver instance
30-
reset resets everything in the running mockserver instance
31-
help [command] display help for command
28+
set <paths...> send prepared expectations up to the mockserver instance
29+
clear <paths...> clear all expectations from the mockserver instance
30+
reset resets all expectations and request logs in the running mockserver instance
31+
get-active [options] <paths...> get all active expectations from the mockserver instance
32+
help [command] display help for command
3233
```
3334

3435
## Installation for development
@@ -65,12 +66,14 @@ File can be placed anywhere. If `-c` or `--config` option is not provided, progr
6566

6667
Concurrency of promises sets, how many promises many promises will be held in the queue at max to resolve. Defaults to `10`.
6768

68-
This limiting is applied for both `set` and `clear` commands.
69+
This limiting is applied for both `set`, `clear` and `get-active` commands.
6970

7071
- `set` is limited for how many expectations requests to mock-server can be sent at once.
7172

7273
- `clear` is limited for how many `expectations.json` files can be processed at once. If the expectations array in the file contains multiple expectations, they will be processed one by one sequentially.
7374

75+
- `get-active` is limited for how many requests to mock-server regarding active expectations for the given expectation of the `.expectations.json` file can be sent at once.
76+
7477
Uses [p-queue](https://github.com/sindresorhus/p-queue) library under the hood.
7578

7679
```bash
@@ -172,10 +175,28 @@ npx expectations clear ./examples/expectations ./examples/expectations2
172175

173176
### Reset MockServer
174177

178+
Resets all expectations and logs in the running mockserver instance.
179+
175180
```bash
176181
npx expectations reset
177182
```
178183

184+
### Get Active Expectations
185+
186+
You have to provide the path(s) to the directory or file containing the expectations.
187+
188+
You may provide option `-s` or `--save` to save the active expectations to the `.json` file.
189+
190+
Otherwise, the expectations are only logged to the console with `trace` log level.
191+
192+
```bash
193+
# retrieves active expectations from the mockserver instance and does NOT save them to the file.
194+
npx expectations -c some/path/to/mockserver.config.json get-active ./examples/expectations/expectation1.json
195+
196+
# retrieves active expectations from the mockserver instance and saves them to the file.
197+
npx expectations -c some/path/to/mockserver.config.json get-active examples/expectations/expectation1.json -s retrieved-active-expectations.json
198+
```
199+
179200
## Logging
180201

181202
Logging is done via [pino.js](https://getpino.io/) library. Currently, there is only the possibility to log to the console.

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@bednarik_radek/mockserver-cli",
3-
"version": "0.1.6",
3+
"version": "0.2.0",
44
"description": "CLI utility for Mock-server client. Allows for easy creation/deletion of expectations on the Mock-server instance.",
55
"main": "index.js",
66
"type": "module",

src/cli/cli.ts

+14
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { createCommand } from "commander";
22
import { setHandler } from "./handlers/set.handler.js";
33
import { clearHandler } from "./handlers/clear.handler.js";
44
import { resetHandler } from "./handlers/reset.handler.js";
5+
import { getActiveHandler } from "./handlers/getActive.handler.js";
6+
import { saveJsonFile } from "../io/io.js";
57

68
export const program = createCommand();
79

@@ -32,3 +34,15 @@ program
3234
.action(async () => {
3335
await resetHandler(program.optsWithGlobals());
3436
});
37+
38+
program
39+
.command("get-active")
40+
.description("get all active expectations from the mockserver instance")
41+
.argument("<paths...>", "paths to the expectations files or dirs")
42+
.option("-s, --save <path>", "save active expectations to file")
43+
.action(async (paths, options) => {
44+
const expectations = await getActiveHandler(paths, program.optsWithGlobals());
45+
if (options.save) {
46+
await saveJsonFile(options.save, expectations);
47+
}
48+
});

src/cli/handlers/getActive.handler.ts

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import Client from "../../client/client.js";
2+
import { logger } from "../../log/logger.js";
3+
import { getAllFilePaths, readJsonFile } from "../../io/io.js";
4+
import { globalOptsHandler } from "./globalOpts.handler.js";
5+
import PQueue from "p-queue";
6+
import { resolve } from "path";
7+
import type { OptionValues } from "commander";
8+
import type { PathOrRequestDefinition } from "mockserver-client/mockServerClient.js";
9+
import { Expectation } from "mockserver-client";
10+
11+
const log = logger.child({ module: "get-active" });
12+
13+
async function getActiveExpectation(client: Client, expectations: PathOrRequestDefinition) {
14+
try {
15+
const response = await client.getActiveExpectations(expectations);
16+
17+
return response;
18+
} catch (error: any) {
19+
log.error("Error getting active expectations:", error);
20+
return null;
21+
}
22+
}
23+
24+
export async function getActiveHandler(paths: string[], options: OptionValues) {
25+
try {
26+
log.trace(`Handling get-active command with args: ${JSON.stringify({ paths, options })}`);
27+
28+
const opts = await globalOptsHandler(options);
29+
const concurrency = parseInt(opts["concurrency"]);
30+
31+
const allPaths: string[] = [];
32+
33+
for (const path of paths) {
34+
const expectationsPaths = await getAllFilePaths(path);
35+
allPaths.push(...expectationsPaths);
36+
}
37+
38+
log.trace(`All expectations filepaths resolved to: ${JSON.stringify(allPaths)}`);
39+
40+
const client = new Client({
41+
proto: opts["config"].proto,
42+
host: opts["config"].host,
43+
port: opts["config"].port,
44+
});
45+
46+
const activeExpectations: Expectation[] = [];
47+
const queue = new PQueue({ concurrency });
48+
49+
queue.on("completed", (result) => {
50+
log.trace(`Retrieved active expectation: ${JSON.stringify(result)}`);
51+
activeExpectations.push(result);
52+
});
53+
54+
log.trace(`Expectations will be set with promises concurrency: ${concurrency}`);
55+
56+
for (const path of allPaths) {
57+
const fullPath = resolve(path);
58+
59+
log.trace(`Getting active expectations from file: ${fullPath}`);
60+
61+
const expectations: Expectation[] = await readJsonFile(fullPath);
62+
63+
for (const expectation of expectations) {
64+
queue.add(() => getActiveExpectation(client, expectation));
65+
}
66+
}
67+
68+
await queue.onIdle();
69+
70+
return activeExpectations;
71+
} catch (error: any) {
72+
log.error(error.message);
73+
throw error;
74+
}
75+
}

src/client/client.ts

+15
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,19 @@ export default class Client {
8282
throw error;
8383
}
8484
}
85+
86+
public async getActiveExpectations(pathOrRequestDefinition: PathOrRequestDefinition) {
87+
try {
88+
log.trace("Getting active expectations");
89+
90+
const response = await this.client.retrieveActiveExpectations(pathOrRequestDefinition);
91+
92+
log.trace(`Active expectations request response: ${JSON.stringify(response)}`);
93+
94+
return response;
95+
} catch (error: any) {
96+
log.error(error.message);
97+
throw error;
98+
}
99+
}
85100
}

src/io/io.ts

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { readFile, opendir, access } from "node:fs/promises";
1+
import { readFile, opendir, access, writeFile } from "node:fs/promises";
22
import { resolve, join } from "node:path";
33
import { logger } from "../log/logger.js";
44

@@ -23,6 +23,21 @@ export async function readJsonFile(filePath: string): Promise<any> {
2323
}
2424
}
2525

26+
export async function saveJsonFile(filePath: string, data: any): Promise<void> {
27+
try {
28+
const fullPath = resolve(filePath);
29+
30+
log.trace(`Saving JSON file: ${fullPath} with data: ${JSON.stringify(data)}}`);
31+
32+
await writeFile(resolve(filePath), JSON.stringify(data, null, 2), "utf-8");
33+
34+
log.trace(`JSON file saved`);
35+
} catch (error: any) {
36+
log.error("Error saving JSON file:", error.message);
37+
throw error;
38+
}
39+
}
40+
2641
export async function getAllFilePaths(directoryPath: string, fileNameEnd = ".expectations.json"): Promise<string[]> {
2742
const filepaths: string[] = [];
2843

0 commit comments

Comments
 (0)