Installations
npm install graphql-codegen-typescript-mock-data
Score
91
Supply Chain
79.2
Quality
80
Maintenance
100
Vulnerability
99.6
License
Developer
ardeois
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
NPM Version
Statistics
134 Stars
296 Commits
46 Forks
3 Watching
5 Branches
31 Contributors
Updated on 20 Sept 2024
Bundle Size
3.44 MB
Minified
1.12 MB
Minified + Gzipped
Languages
TypeScript (99.66%)
JavaScript (0.29%)
Shell (0.05%)
Total Downloads
Cumulative downloads
Total Downloads
8,678,041
Last day
12.4%
20,871
Compared to previous day
Last week
10.4%
96,636
Compared to previous week
Last month
5%
391,539
Compared to previous month
Last year
53.8%
4,859,511
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
9
Peer Dependencies
1
Dev Dependencies
22
graphql-codegen-typescript-mock-data
Description
GraphQL Codegen Plugin for building mock data based on the schema.
Installation
yarn add -D graphql-codegen-typescript-mock-data
Configuration
typesFile (string
, defaultValue: null
)
Defines the file path containing all GraphQL types. This file can also be generated through graphql-codegen
useTypeImports(boolean, defaultValue: false)
Will use import type {} rather than import {} when importing only types. This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option
addTypename (boolean
, defaultValue: false
)
Adds __typename
property to mock data
enumsAsTypes (boolean
, defaultValue: false
)
Changes enums to TypeScript string union types
terminateCircularRelationships (boolean | 'immediate'
, defaultValue: false
)
When enabled, prevents circular relationships from triggering infinite recursion. After the first resolution of a specific type in a particular call stack, subsequent resolutions will return an empty object cast to the correct type.
When enabled with immediate
, it will only resolve the relationship once, independently of the call stack. Use this option if you're experiencing out of memory
errors while generating mocks.
prefix (string
, defaultValue: a
for consonants & an
for vowels)
The prefix to add to the mock function name. Cannot be empty since it will clash with the associated
typescript definition from @graphql-codegen/typescript
listElementCount (number
, defaultValue: 1
)
How many elements should be generated for lists. For example, with listElementCount: 3
a schema field names: [String!]!
would generate 3
names in each mock.
enumValues (string
, defaultValue: change-case-all#pascalCase
)
Changes the case of the enums. The format of the converter must be a valid module#method
. You can also use keep
to
keep all GraphQL names as-is. Available case functions in change-case-all
are camelCase
, capitalCase
, constantCase
,
dotCase
, headerCase
, noCase
, paramCase
, pascalCase
, pathCase
, sentenceCase
, snakeCase
, lowerCase
,
localeLowerCase
, lowerCaseFirst
, spongeCase
, titleCase
, upperCase
, localeUpperCase
and upperCaseFirst
See more
typeNames (string
, defaultValue: change-case-all#pascalCase
)
Changes the case of types. The format of the converter must be a valid module#method
. You can also use keep
to
keep all GraphQL names as-is. Available case functions in change-case-all
are camelCase
, capitalCase
, constantCase
,
dotCase
, headerCase
, noCase
, paramCase
, pascalCase
, pathCase
, sentenceCase
, snakeCase
, lowerCase
,
localeLowerCase
, lowerCaseFirst
, spongeCase
, titleCase
, upperCase
, localeUpperCase
and upperCaseFirst
See more
scalars ({ [Scalar: string]: GeneratorOptions }
, defaultValue: undefined
)
Allows you to define mappings for your custom scalars. Allows you to map any GraphQL Scalar to a casual embedded generator (string or function key) with optional arguments, or a or faker generator with optional arguments
For detailed configuration options, see GeneratorOptions documentation.
Examples using casual
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: date # gets translated to casual.date()
With arguments
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: # gets translated to casual.date('YYYY-MM-DD') 5 generator: date 6 arguments: 'YYYY-MM-DD'
Examples using faker
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: date.past # gets translated to faker.date.past()
With arguments
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: # gets translated to faker.date.past(10) 5 generator: date.past 6 arguments: 10
Custom value generator
1plugins: 2 - add: "import { arrayBufferGenerator } from '../generators';" 3 - typescript-mock-data: 4 scalars: 5 ArrayBuffer: arrayBufferGenerator()
typesPrefix (string
, defaultValue: '')
Useful if you have globally exported types under a certain namespace. e.g If the types file is something like this
declare namespace Api {
type User {
...
}
}
Setting the typesPrefix
to Api.
will create the following mock data
export const aUser = (overrides?: Partial<Api.User>): Api.User => {
enumsPrefix (string
, defaultValue: '')
Similar to typesPrefix
, but for enum types
declare namespace Api {
enum Status {
...
}
}
Setting the enumsPrefix
to Api.
will create the following mock data
export const aUser = (overrides?: Partial<User>): User => {
status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Api.Status.Online,
}
typeNamesMapping ({ [typeName: string]: string }
, defaultValue: {}
)
Allows you to define mappings to rename the types. This is useful when you want to override the generated type name. For example, if you have a type called User
and you want to rename it to RenamedUser
you can do the following:
plugins:
- typescript-mock-data:
typesFile: '../generated-types.ts'
typeNamesMapping:
User: RenamedUser
This will generate the following mock function:
export const aUser = (overrides?: Partial<RenamedUser>): RenamedUser => {
Note: It is not possible to rename your enums using this option.
transformUnderscore (boolean
, defaultValue: true
)
When disabled, underscores will be retained for type names when the case is changed. It has no effect if typeNames
is set to keep
.
dynamicValues (boolean
, defaultValue: false
)
When enabled, values will be generated dynamically when the mock function is called rather than statically when the mock function is generated. The values are generated consistently from a casual seed that can be manually configured using the generated seedMocks(seed: number)
function, as shown in this test.
useImplementingTypes (boolean
, defaultValue: false
)
When enabled, it will support the useImplementingTypes GraphQL codegen configuration.
- When a GraphQL interface is used for a field, this flag will use the implementing types, instead of the interface itself.
defaultNullableToNull (boolean
, defaultValue: false
)
When enabled, it will set all nullable fields to null per default instead of generating a value.
fieldGeneration ({ [typeName: string]: { [fieldName: string]: GeneratorOptions } }
, defaultValue: undefined
)
This setting allows you to add specific generation to a field for a given type. For example if you have a type called User
and a field called birthDate
you can override any generated value there as follows:
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: date.future 5 fieldGeneration: 6 User: 7 birthDate: date.past
Note that even if birthDate
is a scalar of Date
type, its value will still be overridden.
If you want to use a specific generator for all fields of a given name, you can declare it under a property called _all
:
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: date.future 5 fieldGeneration: 6 _all: 7 email: internet.email 8 AdminUser: 9 email: 'admin@email.com'
In the above example all resolvers with the name email
will use the internet.email
generator. However since we specified a specific email for AdminUser
that will take precedence over the _all
generated value.
For detailed configuration options, see GeneratorOptions documentation.
generateLibrary ('casual' | 'faker'
, defaultValue: 'faker'
)
Select a library to generate mock values. The default is faker, Other options include casual casual is not maintained and will be remove in future major versions. faker is useful when you want to use a mock function with the dynamicValues option enabled in the browser.
GeneratorOptions
type
This type is used in scalars
and fieldGeneration
options.
Examples using faker
With arguments
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: # gets translated to faker.date.past(10) 5 generator: date.past 6 arguments: 10
With multiple arguments
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Description: # gets translated to faker.lorem.paragraphs(3, '\n') 5 generator: lorem.paragraphs 6 arguments: 7 - 3 8 - '\n'
Shorthand if you don't have arguments
1plugins: 2 - typescript-mock-data: 3 scalars: 4 Date: date.past # gets translated to faker.date.past()
With extra function call
1fieldName: # gets translated to faker.date.past().toLocaleDateString() 2 generator: date.past 3 extra: 4 function: toLocaleDateString
With extra function call arguments
1fieldName: # gets translated to faker.date.past().toLocaleDateString('en_GB) 2 generator: date.past 3 extra: 4 function: toLocaleDateString 5 arguments: 'en_GB'
Custom value generator
1# gets translated as is 2fieldName: arrayBufferGenerator()
Examples using casual (deprecated)
Shorthand if you don't have arguments
1fieldName: date # gets translated to casual.date()
With arguments
1fieldName: # gets translated to casual.date('YYYY-MM-DD') 2 generator: date 3 arguments: 'YYYY-MM-DD'
With multiple arguments
1fieldName: # gets translated to casual.integer(-100, 100) 2 generator: integer 3 arguments: 4 - -100 5 - 100
With extra function call
1fieldName: # gets translated to casual.integer.toFixed() 2 generator: integer 3 extra: 4 function: toFixed
With extra function call arguments
1fieldName: # gets translated to casual.integer.toFixed(3) 2 generator: integer 3 extra: 4 function: toFixed 5 arguments: 3
Examples of usage
codegen.yml
1overwrite: true 2schema: schema.graphql 3generates: 4 src/generated-types.ts: 5 plugins: 6 - 'typescript' 7 src/mocks/generated-mocks.ts: 8 plugins: 9 - typescript-mock-data: 10 typesFile: '../generated-types.ts' 11 enumValues: upper-case#upperCase 12 typeNames: keep 13 scalars: 14 AWSTimestamp: number.int # gets translated to faker.number.int()
With eslint-disable
rule
codegen.yml
1overwrite: true 2schema: schema.graphql 3generates: 4 src/generated-types.ts: 5 plugins: 6 - 'typescript' 7 src/mocks/generated-mocks.ts: 8 plugins: 9 - add: 10 content: '/* eslint-disable @typescript-eslint/no-use-before-define,@typescript-eslint/no-unused-vars,no-prototype-builtins */' 11 - typescript-mock-data: 12 typesFile: '../generated-types.ts' 13 enumValues: upper-case#upperCase 14 typeNames: keep 15 scalars: 16 AWSTimestamp: number.int # gets translated to faker.number.int()
Example of generated code
Given the following schema:
1scalar AWSTimestamp 2 3type Avatar { 4 id: ID! 5 url: String! 6} 7 8type User { 9 id: ID! 10 login: String! 11 avatar: Avatar 12 status: Status! 13 updatedAt: AWSTimestamp 14} 15 16type Query { 17 user: User! 18} 19 20input UpdateUserInput { 21 id: ID! 22 login: String 23 avatar: Avatar 24} 25 26enum Status { 27 ONLINE 28 OFFLINE 29} 30 31type Mutation { 32 updateUser(user: UpdateUserInput): User 33}
The code generated will look like:
1export const anAvatar = (overrides?: Partial<Avatar>): Avatar => { 2 return { 3 id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '0550ff93-dd31-49b4-8c38-ff1cb68bdc38', 4 url: overrides && overrides.hasOwnProperty('url') ? overrides.url! : 'aliquid', 5 }; 6}; 7 8export const anUpdateUserInput = (overrides?: Partial<UpdateUserInput>): UpdateUserInput => { 9 return { 10 id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : '1d6a9360-c92b-4660-8e5f-04155047bddc', 11 login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'qui', 12 avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : anAvatar(), 13 }; 14}; 15 16export const aUser = (overrides?: Partial<User>): User => { 17 return { 18 id: overrides && overrides.hasOwnProperty('id') ? overrides.id! : 'a5756f00-41a6-422a-8a7d-d13ee6a63750', 19 login: overrides && overrides.hasOwnProperty('login') ? overrides.login! : 'libero', 20 avatar: overrides && overrides.hasOwnProperty('avatar') ? overrides.avatar! : anAvatar(), 21 status: overrides && overrides.hasOwnProperty('status') ? overrides.status! : Status.Online, 22 updatedAt: overrides && overrides.hasOwnProperty('updatedAt') ? overrides.updatedAt! : 1458071232, 23 }; 24};
Usage in tests
Those helper functions can be used in our unit tests:
1const user = aUser({ login: 'johndoe' }); 2 3// will create a user object with `login` property overridden to `johndoe`
Dealing with Timezone
If some properties use generated dates, the result could different depending on the timezone of your machine.
To force a timezone, you can set environment variable TZ
:
1TZ=UTC graphql-codegen
This will force the timezone to UTC
, whatever the timezone of your machine or CI
Contributing
Feel free to open issues and pull requests. We always welcome support from the community.
To run this project locally:
- Use Node >= 16
- Make sure that you have the latest Yarn version (https://yarnpkg.com/lang/en/docs/install/)
- Clone this repo using
git clone
- Run
yarn
- Run
yarn build
to build the package - Run
yarn test
to make sure everything works
License
MIT
No vulnerabilities found.
Reason
10 commit(s) and 5 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
SAST tool is run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Info: all commits (12) are checked with a SAST tool
Reason
6 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Reason
Found 8/28 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/build.yml:1
- Warn: no topLevel permission defined: .github/workflows/codeql-analysis.yml:1
- Warn: no topLevel permission defined: .github/workflows/deploy.yml:1
- Warn: no topLevel permission defined: .github/workflows/lint.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/build.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/build.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/build.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:33: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:46: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:57: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql-analysis.yml:71: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/codeql-analysis.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/deploy.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/deploy.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/deploy.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/deploy.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/deploy.yml:28: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/deploy.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/lint.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/lint.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/lint.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/ardeois/graphql-codegen-typescript-mock-data/test.yml/main?enable=pin
- Info: 0 out of 16 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
5.1
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to graphql-codegen-typescript-mock-data
@graphql-codegen/core
<p align="center"> <img src="https://github.com/dotansimha/graphql-code-generator/blob/master/logo.png?raw=true" /> </p>
@graphql-codegen/cli
<p align="center"> <img src="https://github.com/dotansimha/graphql-code-generator/blob/master/logo.png?raw=true" /> </p>
graphql-codegen-typescript-validation-schema
GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema
@linear/sdk
The Linear Client SDK for interacting with the Linear GraphQL API