faker-js / faker

Generate massive amounts of fake data in the browser and node.js
https://fakerjs.dev
Other
12.56k stars 903 forks source link

Add exclude on enum faker.helpers.enumValue #2994

Open mikiyasET opened 3 months ago

mikiyasET commented 3 months ago

Clear and concise description of the problem

I wanted to seed some data to the database and one of the tables needs image type and an image so while seeding I couldn't add a file since it needs to be uploaded to the server so for the seed purpose only I wanted to remove the file value from the enum or exclude but there is no option for that

Suggested solution

enum ImageType {
  file
  link
  emoji
  constant
}

const imageType = faker.helpers.enumValue(ImageType, {exclude: [ImageType.file]});
github-actions[bot] commented 3 months ago

Thank you for your feature proposal.

We marked it as "waiting for user interest" for now to gather some feedback from our community:

ST-DDT commented 3 months ago

As a workaround - although less convenient - you can use the following:

faker.helpers.arrayElement([ImageType.link, ImageType.emoji, ImageType.constant]);
xDivisionByZerox commented 2 months ago

As a workaround - although less convenient - you can use the following:

faker.helpers.arrayElement([ImageType.link, ImageType.emoji, ImageType.constant]);

You could also build a function that is basically the implementation of helpers.enumValue():

function enumValue<T extends Record<string | number, string | number>>(enumObj: T, exclude: (keyof T)[]): T[keyof T] {
  const keys: Array<keyof T> = Object.keys(enumObj)
    // ignore numeric keys added by TypeScript
    .filter((key) =>Number.isNaN(Number(key)))
    // this line is what faker is missing
    .filter((key) =>!exclude.includes(key));
  const key = faker.helpers.arrayElement(keys);
  return enumObj[key];
}

// usage

enum ImageType {
  file,
  link,
  emoji,
  constant,
}
cosnt value = enumValue(ImageType , ['file']);
console.log(value); // 1 | 2 | 3 => ImageType.link | ImageType.emoji | ImageType.constant

I'd still consider this a workaround.


Working TypeScrip Playground Example