Skip to content

Commit

Permalink
Merge branch 'next' into infra/unicorn/prefer-top-level-await
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT authored Feb 25, 2024
2 parents f7a1b81 + a6eda6f commit 8a1376f
Show file tree
Hide file tree
Showing 22 changed files with 344 additions and 1,608 deletions.
3 changes: 3 additions & 0 deletions .github/renovate.json5
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
"helpers:pinGitHubActionDigests"
],
"labels": ["c: dependencies"],
"lockFileMaintenance": {
"enabled": true
},
"reviewersFromCodeOwners": true,
"rangeStrategy": "bump",
"packageRules": [
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,15 @@ jobs:
pnpm run build
pnpm run test -u
continue-on-error: true
env:
CI_PREFLIGHT: true

- name: Check diff
id: diff
run: |
git add .
git diff --cached --exit-code
git diff --cached --name-only | sed -E 's/^(.*)$/::error file=\1,title=Diff detected::Please run `pnpm run preflight` and commit the changes./'
git diff --cached --name-only --exit-code
continue-on-error: true

- name: Transpile ts
Expand Down
1 change: 0 additions & 1 deletion docs/.vitepress/api-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export const apiPages = [
{ text: 'Number', link: '/api/number.html' },
{ text: 'Person', link: '/api/person.html' },
{ text: 'Phone', link: '/api/phone.html' },
{ text: 'Random', link: '/api/random.html' },
{ text: 'Science', link: '/api/science.html' },
{ text: 'String', link: '/api/string.html' },
{ text: 'System', link: '/api/system.html' },
Expand Down
4 changes: 4 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ const config: UserConfig<DefaultTheme.Config> = {
text: 'Randomizer',
link: '/guide/randomizer',
},
{
text: 'Unique Values',
link: '/guide/unique',
},
{
text: 'Upgrading to v9',
link: '/guide/upgrading',
Expand Down
58 changes: 58 additions & 0 deletions docs/guide/unique.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Unique Values

In general, Faker methods do not return unique values.

```ts
faker.seed(55);
faker.animal.type(); //'cat'
faker.animal.type(); //'bird'
faker.animal.type(); //'horse'
faker.animal.type(); //'horse'
```

Some methods and locales use much smaller data sets than others. For example, `faker.animal.type` has only 13 possible animals to choose from. In contrast, `faker.person.fullName()` pulls from a list of hundreds of first names, surnames, and prefixes/suffixes, so it can generate hundreds of thousands of unique names. Even then, the [birthday paradox](https://en.wikipedia.org/wiki/Birthday_Paradox) means that duplicate values will quickly be generated.

Sometimes, you want to generate unique values. For example, you may wish to have unique values in a database email column.
There are a few possible strategies for this:

1. Use `faker.helpers.uniqueArray()` if you want to generate all the values at one time. For example:

```ts
faker.helpers.uniqueArray(faker.internet.email, 1000); // will generate 1000 unique email addresses
```

2. If there are insufficient values for your needs, consider prefixing or suffixing values with your own sequential values, for example you could prefix `1.`, `2.` to each generated email in turn.

3. Build your own logic to keep track of a set of previously generated values and regenerate values as necessary if a duplicate is generated

4. Use a third party package to enforce uniqueness such as [enforce-unique](https://github.com/MansurAliKoroglu/enforce-unique)

Note you can supply a maximum time (in milliseconds) or maximum number of retries.

```js
import { EnforceUniqueError, UniqueEnforcer } from 'enforce-unique';

const uniqueEnforcerEmail = new UniqueEnforcer();

function createRandomUser() {
const firstName = faker.person.firstName();
const lastName = faker.person.lastName();
const email = uniqueEnforcerEmail.enforce(
() =>
faker.internet.email({
firstName,
lastName,
}),
{
maxTime: 50,
maxRetries: 50,
}
);

return {
firstName,
lastName,
email,
};
}
```
65 changes: 65 additions & 0 deletions docs/guide/upgrading_v9/2661.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
### Remove helpers.unique

Prior to v9, Faker provided a [`faker.helpers.unique()`](https://v8.fakerjs.dev/api/helpers.html#unique) method which had a global store to keep track of duplicates. This was removed in v9.

Please see the [unique values guide](/guide/unique) for alternatives.

For example, many simple use cases can use [`faker.helpers.uniqueArray`](https://v8.fakerjs.dev/api/helpers.html#uniqueArray). Or you can migrate to a third party package such as `enforce-unique`:

Basic example:

```js
// OLD
const name = faker.helpers.unique(faker.person.firstName);

// NEW
import { UniqueEnforcer } from 'enforce-unique';
//const { UniqueEnforcer } = require("enforce-unique") // CJS

const enforcerName = new UniqueEnforcer();
const name = enforcerName.enforce(faker.person.firstName);
```

With parameters:

```js
// OLD
const stateCode = faker.helpers.unique(faker.location.state, [
{
abbreviated: true,
},
]);

// NEW
import { UniqueEnforcer } from 'enforce-unique';

const enforcerState = new UniqueEnforcer();
const stateCode = enforcerState.enforce(() =>
faker.location.state({
abbreviated: true,
})
);
```

With options:

```js
// OLD
const city = faker.helpers.unique(faker.location.city, [], {
maxRetries: 100,
maxTime: 1000,
});

// NEW
import { UniqueEnforcer } from 'enforce-unique';

const enforcer = new UniqueEnforcer();
const city = enforcer.enforce(faker.location.city, {
maxRetries: 100,
maxTime: 1000,
});
```

::: tip Note
`enforce-unique` does not support the `exclude` or `store` options. If you were previously using these, you may wish to build your own unique logic instead.
:::
12 changes: 12 additions & 0 deletions docs/guide/upgrading_v9/2678.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
### Remove deprecated random module

Removed deprecated random module

| old | replacement |
| ----------------------------- | ----------------------------------------------- |
| `faker.random.alpha()` | `faker.string.alpha()` |
| `faker.random.alphaNumeric()` | `faker.string.alphanumeric()` |
| `faker.random.locale()` | `faker.helpers.objectKey(allLocales/allFakers)` |
| `faker.random.numeric()` | `faker.string.numeric()` |
| `faker.random.word()` | `faker.lorem.word()` or `faker.word.sample()` |
| `faker.random.words()` | `faker.lorem.words()` or `faker.word.words()` |
22 changes: 22 additions & 0 deletions docs/guide/upgrading_v9/2682.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### Remove deprecated faker constructor and deprecated JS backwards compatibility

Removed deprecated faker constructor, so it is not possible anymore to just pass a locale string identifier.

Also removed the accessors and method that were only for JS backwards compatibility.

- `get/set locales`
- `get/set locale`
- `get/set localeFallback`
- `setLocale`

To use the new constructor, you need to pass a locale object like:

```ts
import { Faker, es, base } from '@faker-js/faker';

// A custom faker instance that does not have any fallbacks
const customEsFakerWithoutFallback = new Faker({ locale: es });

// A custom faker instance that has only base-data as fallback, but not english data
const customEsFakerWithFallback = new Faker({ locale: [es, base] });
```
16 changes: 16 additions & 0 deletions docs/guide/upgrading_v9/2685.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
### Usage of TypeScript 5 Features

_This upgrade is an extension to_ [#1953](./1953.md)

The helpers module now uses TS5 features, so if you are using Faker with TypeScript, you must use TS5.

```ts
// v8
faker.helpers.arrayElement([1, 2, 3]); // number
faker.helpers.arrayElement([1, 2, 3] as const); // 1 | 2 | 3

// v9
faker.helpers.arrayElement([1, 2, 3]); // 1 | 2 | 3
```

If you are unable to upgrade to TS5, you have to keep using Faker v8.
41 changes: 1 addition & 40 deletions docs/guide/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,45 +233,6 @@ Here, we could also pass in the `sex` value as argument, but in our use-case the
By doing this first, we are able to pass both names into the `email` generation function.
This allows the value to be more reasonable based on the provided arguments.

But we can take this even another step further.
Opposite to the `_id` property that uses an `uuid` implementation, which is unique by design, the `email` property potentially isn't.
But, in most use-cases, this would be desirable.

Faker has your back, with another helper method:

```ts {7-10}
import { faker } from '@faker-js/faker';

function createRandomUser(): User {
const sex = faker.person.sexType();
const firstName = faker.person.firstName(sex);
const lastName = faker.person.lastName();
const email = faker.helpers.unique(faker.internet.email, [
firstName,
lastName,
]);

return {
_id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email,
firstName,
lastName,
sex,
subscriptionTier: faker.helpers.arrayElement(['free', 'basic', 'business']),
};
}

const user = createRandomUser();
```

By wrapping Faker's `email` function with the [`unique`](../api/helpers.md#unique) helper function, we ensure that the return value of `email` is always unique.

::: warning
The `faker.helpers.unique` is targeted to be removed from Faker in the future.
Please have a look at the issue [#1785](https://github.com/faker-js/faker/issues/1785).
We will update these docs once a replacement is available.
:::
Unlike the `_id` property that uses an `uuid` implementation, which has a low chance of duplicates, the `email` function is more likely to produce duplicates, especially if the call arguments are similar. We have a dedicated guide page on generating [unique values](unique).

Congratulations, you should now be able to create any complex object you desire. Happy faking 🥳.
9 changes: 1 addition & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,7 @@
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "index.d.ts",
"typesVersions": {
">=4.0": {
"*": [
"dist/types/*"
]
}
},
"types": "dist/types/index.d.ts",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
Expand Down
Loading

0 comments on commit 8a1376f

Please sign in to comment.