Skip to content

Commit

Permalink
JavaScript (v3): Update utils. (awsdocs#6950)
Browse files Browse the repository at this point in the history
- Update the getUniqueName util to throw an error if a prefix is not passed in.
- Add a validateArgs util for checking parseArg options marked as required.
  • Loading branch information
cpyle0819 authored Oct 3, 2024
1 parent 790b580 commit 347e86d
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 9 deletions.
8 changes: 4 additions & 4 deletions javascriptv3/example_code/libs/tests/util-string.unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ describe("util-string", () => {
expect(u1).not.toEqual(u2);
});

it("should return undefined if a falsy value is passed in", () => {
expect(getUniqueName()).toBeUndefined();
expect(getUniqueName("")).toBeUndefined();
expect(getUniqueName(0)).toBeUndefined();
it("should throw an error if a falsy value is passed in for the prefix", () => {
expect(() => getUniqueName()).toThrowError();
expect(() => getUniqueName("")).toThrowError();
expect(() => getUniqueName(0)).toThrowError();
});
});

Expand Down
29 changes: 29 additions & 0 deletions javascriptv3/example_code/libs/utils/util-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,32 @@ export const setEnv = (/** @type {string} */ key, value) => {
* @param {string | URL} fileUrl
*/
export const isMain = (fileUrl) => process.argv[1] === fileURLToPath(fileUrl);

/**
* @typedef {import("node:util").ParseArgsConfig} ParseArgsConfig
* @typedef {ReturnType<import("node:util").parseArgs>} ParsedResults
*
* @param {import("node:util").ParseArgsConfig} config
* @param {ParsedResults} results
* @returns {{ errors: string[] | null }}
*/
export const validateArgs = (config, results) => {
if (!config.options) {
return {};
}

/** @type {string[] | null} */
let errors = null;

for (const option in config.options) {
const optionRequired = config.options[option]?.required;
const optionPresent = Object.hasOwn(results.values, option);

if (optionRequired && !optionPresent) {
errors = errors ?? [];
errors.push(`Missing required argument "${option}".`);
}

return { errors };
}
};
14 changes: 9 additions & 5 deletions javascriptv3/example_code/libs/utils/util-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
import { v4 as uuidv4 } from "uuid";

/**
* @param {string} name
* @param {string} prefix
*/
export const getUniqueName = (name) => {
if (!name) {
return;
export const getUniqueName = (prefix) => {
class GetUniqueNameError extends Error {
name = GetUniqueNameError.name;
}

return `${name.toLowerCase()}-${uuidv4()}`;
if (!prefix) {
throw new GetUniqueNameError("Prefix is missing.");
}

return `${prefix.toLowerCase()}-${uuidv4()}`;
};

/**
Expand Down

0 comments on commit 347e86d

Please sign in to comment.