0.0.2 • Published 3 years ago

ts-mimic v0.0.2

Weekly downloads
-
License
-
Repository
-
Last release
3 years ago

TypeScript Data Generator

What

Use TypeScript to generate endless mock data.

Why

TypeScript's type system is very expressive and easy to use, making it perfect to define the shape of mock data.

ts-mimic was built to easily define mock data sent to EventHub: https://eventhub.chriscaruso.dev

How

ts-mimic provides a set of types that map to specific types of mock data. It can even guess the kind of mock data just from property names!

Installation

Install this package through npm

npm i ts-mimic typescript@~4.1.5

Examples

Try it out: https://mimic.chriscaruso.dev

Simple example

import { mimic } from 'ts-mimic';

const ts = `
interface Person {
    firstName: asFirstName; // Use built in mock data generators. See below for a complete list.
    lastName: asLastName;
    age: asNumberRange<20, 30>; // Some mock data generators can take parameters to customize them.
    address; // Auto detect mock data from the property name.
    secondaryAddress?: asSecondaryAddress; // Properties can be optional. These have a 50% chance of being undefined.
    state?;
    city: asCity;
    image: Sometimes<.75, asImagePeople>; // Sometimes is a special type that lets you specify the chance a value will be defined
}`;

const { map: { Person } } = mimic(ts);
const mockPerson = Person();

console.log(mockPerson);

Possible output

{
    firstName: "Zion",
    lastName: "Block",
    age: 23,
    address: "25612 Rath Avenue",
    secondaryAddress: undefined,
    state: "Utah",
    city: "Alvinaview",
    image: "http://placeimg.com/640/480/people",
}

Full example

Play with this example live at https://mimic.chriscaruso.dev

import { mimic } from 'ts-mimic';

const ts = `
interface Name {
    firstName: asFirstName; // Use built in mock data generators. See below for a complete list.
    lastName: asLastName;
}

interface Address {
    address; // Auto detect mock data
    secondaryAddress?: asSecondaryAddress; // Properties can be optional. These have a 50% chance of being undefined
    state?;
    city: \`City: \${asCity}\`; // Use template literals to define compound strings
}

interface BitcoinWallet {
    type: 'bitcoin'; // Use type literals for static data
    bitcoinAddress;
}

interface EtheriumWallet {
    type: 'etherium';
    etheriumAddress;
}

// Use type aliases to create convenient types (ex. union, array, literal types)
type DigitalWallet = BitcoinWallet | EtheriumWallet; // Union types for an equal chance at any of them

interface Person {
    name: Name; // Reference other defined types
    address: Address;
    digitalWallet?: DigitalWallet;
    age: asNumberRange<20, 30>; // Some mock data generators can take parameters to customize them.
    image?: Sometimes<.75, asImagePeople>; // Sometimes is a special type that lets you specify the chance a value will be defined
}

// Use type aliases to represent type literals
type Team = {
    members: BoundArray<Person, 6, 2>; // BoundArray is a special type that lets you specify the range of an array
};

// Use type aliases to represent top level array types
type People = Person[]; // Arrays have a random range of 0 to 10 elements

// Use tuples to represent more precise arrays
type Couple = [Person, Person];`;

const { definitions } = mimic(ts);

// Print out each generator's possible output
for (const { name, generator } of definitions) {
    console.log(
        name, 
        generator(),
    );
}

Provided types

Special types

NameParametersReturn typeDescriptionExample
BoundArrayT: any Max: number Min?: number = 0T[]Specifies the chance T will be definedBoundArray<asEmail, 20, 10>
SometimesChance: number T: anyT \| undefinedSpecifies the chance T will be definedSometimes<.7, asEmail>

Generator types

NameParametersReturn typeExample output
asAlphaCount?: number = 1 UpperCase?: boolean = falsestring"n"
asAlphaNumericCount?: number = 1string"t"
asArrayElementstring"a"
asAvatarstring"https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg"
asBitcoinAddressstring"3B7qyhh8KcSwnYoYPvfPHmxCSawHutn"
asBooleanbooleantrue
asCardinalDirectionstring"West"
asCatchPhraseAdjectivestring"Self-enabling"
asCatchPhraseDescriptorstring"multimedia"
asCatchPhraseNounstring"moratorium"
asCitystring"Brockberg"
asCityPrefixstring"Lake"
asCitySuffixstring"berg"
asCommerceColorstring"lime"
asCommonFileExtstring"jpg"
asCommonFileNameExt?: string Type?: stringstring"buckinghamshire.gif"
asCommonFileTypestring"application"
asCompanyCatchPhrasestring"User-centric fault-tolerant alliance"
asCompanyNameFormat?: stringstring"O'Conner - Littel"
asCompanySuffixstring"LLC"
asCountrystring"Djibouti"
asCountryCodestring"CA"
asCountystring"Borders"
asCreditCardCVVstring"076"
asCreditCardNumberProvider?: stringstring"3528-6276-6216-8478"
asCurrencyAmountMin?: number Max?: number Dec?: number Symbol?: stringstring"120.35"
asCurrencyCodestring"DZD"
asCurrencyNamestring"Indian Rupee"
asCurrencySymbolstring"¥"
asDatabaseCollationstring"utf8_unicode_ci"
asDatabaseColumnstring"status"
asDatabaseEnginestring"InnoDB"
asDatabaseTypestring"tinyint"
asDateBetweenFromDate: string ToDate: stringstring"2021-04-19T08:38:54.605Z"
asDateFutureYears?: number DateFrom?: stringstring"2021-05-23T11:37:10.412Z"
asDatePastYears?: number DateFrom?: stringstring"2021-01-30T15:27:04.763Z"
asDateRecentDays?: number DateFrom?: stringstring"2021-03-26T01:21:00.681Z"
asDateSoonDays?: number DateFrom?: stringstring"2021-03-27T06:11:06.507Z"
asDepartmentstring"Health"
asDirectionstring"Southwest"
asDirectoryPathstring"/root"
asDomainNamestring"tanner.com"
asDomainSuffixstring"org"
asDomainWordstring"tommie"
asEmailFirstName?: string LastName?: string Provider?: stringstring"Frankie27@yahoo.com"
asEthereumAddressstring"0x2c5ffaafb99bbf3ae3753a467cfa4f8fd225dea7"
asExampleEmailFirstName?: string LastName?: stringstring"Ashlynn_Borer49@example.org"
asFileExtMimeType?: stringstring"metalink"
asFileNameExt?: string Type?: stringstring"loan.ecelp9600"
asFilePathstring"/home/human_resource_optimized.sub"
asFileTypestring"x-shader"
asFinanceAccountLength?: numberstring"34792807"
asFinanceAccountNamestring"Auto Loan Account"
asFinanceTransactionDescriptionstring"payment transaction at Batz, Lowe and Hyatt using card ending with ***1236 for HUF 70.61 in account ***74200311",
asFinanceTransactionTypestring"deposit"
asFirstNameGender?: 'male' \| 'female' \| 'm' \| 'f'string"Oswaldo"
asFloatMax?: numbernumber30751.39
asFloatRangeMin?: number Max?: number Precision?: numbernumber69423.14
asGenderstring"Trans Female"
asGenrestring"Pop"
asGitBranchstring"feed-quantify"
asGitCommitEntryMerge?: boolean = falsestring"commit 1ba59e0b835d2b870364e1d6da03770a1eb96d7b\r\nAuthor: Angus Keelin <Ron69@yahoo.com>\r\nDate: Thu Mar 25 2021 10:15:00 GMT-0700 (Pacific Daylight Time)\r\n\r\n    parse open-source application\r\n",
asGitCommitMessagestring"hack primary interface"
asGitCommitShastring"5f80887d406c9748ad1ec07a8b9815ff5cf9593c"
asGitShortShastring"0068808"
asHackerAbbreviationstring"AI"
asHackerAdjectivestring"open-source"
asHackerNounstring"application"
asHackerPhrasestring"We need to reboot the mobile FTP driver!"
asHackerVerbstring"copy"
asHackingVerbstring"hacking"
asHexaDecimalCount?: numberstring"0xa"
asImageWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/nightlife"
asImageAbstractWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/abstract"
asImageAnimalWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/animals"
asImageBusinessWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/business"
asImageCatsWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/cats"
asImageCityWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/city"
asImageDataUriWidth?: number = 640 Height?: number = 480 Color?: stringstring"data:image/svg+xm;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20baseProfile%3D%22full%22%20width%3D%22undefined%22%20height%3D%22undefined%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22grey%22%2F%3E%3Ctext%20x%3D%22NaN%22%20y%3D%22NaN%22%20font-size%3D%2220%22%20alignment-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22white%22%3Eundefinedxundefined%3C%2Ftext%3E%3C%2Fsvg%3E",
asImageFashionWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/fashion"
asImageFoodWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/food"
asImageNatureWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/nature"
asImageNightlifeWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/nightlife"
asImagePeopleWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/people"
asImageSportsWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/sports"
asImageTechnicsWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/technics"
asImageTransportWidth?: number = 640 Height?: number = 480string"http://placeimg.com/640/480/transport"
asImageUrlWidth?: number = 640 Height?: number = 480 Category?: string Randomize?: boolean Https? boolean = falsestring"http://placeimg.com/640/480",
asInternetAvatarstring"https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg"
asIPstring"153.152.29.108"
asIPv6string"04fb:cca8:bc84:bbde:16bd:5086:c285:09b3"
asJobAreastring"Usability"
asJobDescriptorstring"Forward"
asJobTitlestring"Human Operations Manager"
asJobTypestring"Engineer"
asJSONstring"{\n \"firstName\": \"Lee\",\n \"lastName\": \"Boyle\",\n \"age\": 23\n}"
asLastNameGender?: 'male' \| 'female' \| 'm' \| 'f'string"Koelpin"
asLatitudeMax?: number Min?: numberstring"-36.3442"
asLocalestring"pt_PT"
asLongitudeMax?: number Min?: numberstring"92.0341"
asLoremLinesLineCount?: numberstring"Hic ut ut ad quia non.\nQuia molestiae iste minima quia ut.\nAut amet vero ea ist cumque quo ducimus aut.\nQuia ipsam quia explicabo doloribus dolor dolores expedita odit.\nAssumenda aperiam inventore.",
asLoremParagraphSentenceCount?: numberstring"Expedita non nemo ut at dolores sint distinctio minus reprehenderit Voluptate sunt et nam voluptas fugit porro. Est ullam quis magnam et. Ratione aut ea. A sed quia facere voluptatibus praesentium.",
asLoremParagraphsParagraphCount?: numberstring"Et qui recusandae blanditiis error officia. Dolor voluptas sapient voluptas fugiat enim tempore. Velit quae et. Accusantium aspernatur at cupiditate. Atque sit expedita. Est explicabo in rerum eos quia pariatur harum quia.\n \rConsequuntur harum et sint aliquam est harum aperiam est minima. Voluptatibus harum qui ipsum debitis animi quis soluta qui. Tenetur ut dolorum non et aliquid. Tempore accusantium non quos voluptatem sunt ut quia corrupti. Perferendis labore sed consequatur eum quo. Pariatur illo in molestias optio excepturi.\n \rIllum iste reprehenderit rerum temporibus voluptatem cumque aliquid minus. Officia quod id consectetur saepe facilis. Porro cum quis sed. Nihil quam non vitae error.",
asLoremSentenceWordCount?: numberstring"Sunt dolorem illo dolore labore voluptate ut est quis."
asLoremSentencesSentenceCount?: numberstring"Et est iste dolorum perspiciatis voluptas quisquam. Magnam reru necessitatibus ut nobis perferendis non nihil aut. Quisquam dolores repudiandae saepe nisi. Qui odit sed ad maxime. Pariatur consequatur nihil sint aut. Rerum nihil nemo molestiae.",
asLoremSlugWordCount?: numberstring"et-vel-tempore"
asLoremTextTimes?: numberstring"Ducimus in enim necessitatibus et ea ipsa omnis aperiam vel. Accusantium quisquam se velit doloremque aspernatur aut et maxime. Odit rem eius labore esse qui id sunt. Facere mollitia praesentium fugit. Labore molestiae consequuntur eos animi.",
asLoremWordLength?: numberstring"architecto"
asLoremWordsWordCount?: numberstring"velit impedit minima"
asMACstring"65:68:a3:c3:04:bf"
asMiddleNamestring"b"
asMimeTypestring"application/vnd.ms-office.activex+xml"
asMonthAbbreviate?: boolean = falsestring"October"
asNearbyGPSCoordinate[string, string]["-63.8772", "-59.3663"]
asNumberMax?: numbernumber1904
asNumberRangeMin?: number Max?: number Precision?: numbernumber62370
asOrdinalDirectionstring"Southeast"
asPasswordLength?: number Memorable?: boolean Pattern?: string Prefix?: numberstring"I8MT5BvdDHh92d_"
asPhoneFormatsstring"!##.!##.#### x####"
asPhoneNumberFormat?: stringstring"(766) 627-9742"
asPhoneNumberFormatPhoneFormatsArrayIndex?: numberstring"758-900-3026"
asPrefixstring"Mr."
asPriceMin?: number Max?: number Dec?: number Symbol?: stringstring"287.00"
asProductstring"Mouse"
asProductAdjectivestring"Refined"
asProductDescriptionstring"New range of formal shirts are designed keeping you in mind. With fits and styling that will mak you stand apart",
asProductMaterialstring"Rubber"
asProductNamestring"Unbranded Plastic Towels"
asProtocolstring"http"
asRGBRed?: number Green?: number Blue?: numberstring"#117846"
asRoutingNumberstring"698889345"
asSecondaryAddressstring"Suite 819"
asSemVerstring"6.0.5"
asStateUseAbbr?: boolean = falsestring"Ohio"
asStateAbbrstring"HI"
asStreetAddressUseFullAddress?: boolean = falsestring"169 Stark Stream"
asStreetNamestring"Mosciski Fork"
asStreetPrefixstring"b"
asStreetSuffixstring"Court"
asSuffixstring"III"
asTimeKind?: 'abbr' \| 'wide' = 'abbr'string"11:51:05 PM"
asTimeZonestring"Pacific/Fiji"
asTitlestring"Central Group Orchestrator"
asUnixTimenumber1616741465160
asUrlstring"http://lenore.biz"
asUserAgentstring"Mozilla/5.0 (Windows; U; Windows NT 6.3) AppleWebKit/533.0.1 (KHTML, like Gecko) Chrome/36.0.843.0 Safar/533.0.1",
asUserNameFirstName?: string LastName?: stringstring"Rhiannon82"
asUUIDstring"62f2c68e-826a-4b1e-994c-1284c6d4c3d8"
asVehiclestring"Kia LeBaron"
asVehicleColorstring"fuchsia"
asVehicleFuelstring"Hybrid"
asVehicleManufacturerstring"Kia"
asVehicleModelstring"Countach"
asVehicleTypestring"SUV"
asVehicleVINstring"T06P0XJUZHLW99828"
asWeekdayAbbreviate?: stringstring"Sunday"
asWordType?: stringstring"Bike"
asWordsCount?: numberstring"deposit sexy transmit"
asZipCodestring"08324"
asZipCodeByStateState?: stringstring"66048-1664"