Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@entity-factory/core

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@entity-factory/core - npm Package Compare versions

Comparing version 0.1.1-alpha.1 to 0.1.2

blueprint/BlueprintFactoryMethodContext.d.ts

1

adapters/Adapter.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Adapter.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=AdapterBlueprintOptions.js.map

@@ -92,5 +92,3 @@ "use strict";

__type = context.__type, idAttribute = context.idAttribute;
generateId = context.generateId !== undefined
? context.generateId
: this.options.generateId;
generateId = context.generateId !== undefined ? context.generateId : this.options.generateId;
if (generateId) {

@@ -119,2 +117,1 @@ idKey_1 = idAttribute || this.options.defaultIdAttribute;

exports.ObjectAdapter = ObjectAdapter;
//# sourceMappingURL=ObjectAdapter.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ObjectAdapterOptions.js.map

@@ -25,2 +25,1 @@ "use strict";

exports.ObjectBlueprint = ObjectBlueprint;
//# sourceMappingURL=ObjectBlueprint.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ObjectBlueprintOptions.js.map

@@ -0,9 +1,9 @@

import { DeepEntityPartial } from '..';
import { Adapter } from '../adapters/Adapter';
import { AdapterBlueprintOptions } from '../adapters/AdapterBlueprintOptions';
import { EntityObjectType } from '../common/EntityObjectType';
import { BlueprintDeepPartial } from './BlueprintDeepPartial';
import { BlueprintDefinitionAfterMethod } from './BlueprintDefinitionAfterMethod';
import { BlueprintDefinitionMethod } from './BlueprintDefinitionMethod';
import { BlueprintOptions } from './BlueprintOptions';
export declare class Blueprint<Entity = any, AdapterType extends Adapter = Adapter, Options extends AdapterBlueprintOptions = {}> {
export declare class Blueprint<Entity = Record<string, any>, AdapterType extends Adapter = Adapter, Options extends AdapterBlueprintOptions = {}> {
private DEFAULT_KEY;

@@ -19,3 +19,3 @@ private entityType;

define(factory: BlueprintDefinitionMethod<Entity>): void;
state(state: string, factory: BlueprintDefinitionMethod<Entity> | BlueprintDeepPartial<Entity>): void;
state(state: string, factory: BlueprintDefinitionMethod<Entity> | DeepEntityPartial<Entity>): void;
afterMaking(callback: BlueprintDefinitionAfterMethod<Entity, AdapterType>): void;

@@ -22,0 +22,0 @@ afterMakingState(state: string, callback: BlueprintDefinitionAfterMethod<Entity, AdapterType>): void;

@@ -139,2 +139,1 @@ "use strict";

exports.Blueprint = Blueprint;
//# sourceMappingURL=Blueprint.js.map

@@ -50,3 +50,2 @@ "use strict";

var faker = require("faker");
var utils_1 = require("../utils");
var BlueprintBuilder = (function () {

@@ -200,29 +199,9 @@ function BlueprintBuilder(profile, factory, adapter) {

return __awaiter(this, void 0, void 0, function () {
var derived, _a, _b, _i, key, value, callback, _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0: return [4, stateFactory(faker)];
var derived;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, stateFactory({ faker: faker, factory: this.factory })];
case 1:
derived = _e.sent();
_a = [];
for (_b in derived)
_a.push(_b);
_i = 0;
_e.label = 2;
case 2:
if (!(_i < _a.length)) return [3, 5];
key = _a[_i];
value = derived[key];
if (!utils_1.isFunction(value)) return [3, 4];
callback = derived[key];
_c = derived;
_d = key;
return [4, callback(this.factory)];
case 3:
_c[_d] = _e.sent();
_e.label = 4;
case 4:
_i++;
return [3, 2];
case 5: return [2, __assign({}, derived, this.partial)];
derived = _a.sent();
return [2, __assign({}, derived, this.partial)];
}

@@ -249,2 +228,1 @@ });

exports.BlueprintBuilder = BlueprintBuilder;
//# sourceMappingURL=BlueprintBuilder.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=BlueprintDefinitionAfterMethod.js.map
/// <reference types="faker" />
import { EntityFactory } from '../EntityFactory';
import { EntityFactoryExecutor } from '../EntityFactoryExecutor';
import FakerStatic = Faker.FakerStatic;
export interface BlueprintDefinitionAfterMethodContext<Adapter> {
factory: EntityFactory;
factory: EntityFactoryExecutor;
faker: FakerStatic;
adapter: Adapter;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=BlueprintDefinitionAfterMethodContext.js.map

@@ -1,4 +0,3 @@

/// <reference types="faker" />
import FakerStatic = Faker.FakerStatic;
import { BlueprintDeepPartial } from './BlueprintDeepPartial';
export declare type BlueprintDefinitionMethod<EntityType> = (fakerInstance: FakerStatic) => Promise<BlueprintDeepPartial<EntityType>>;
import { DeepEntityPartial } from '..';
import { BlueprintFactoryMethodContext } from './BlueprintFactoryMethodContext';
export declare type BlueprintDefinitionMethod<EntityType> = (context: BlueprintFactoryMethodContext) => Promise<DeepEntityPartial<EntityType>>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=BlueprintDefinitionMethod.js.map

@@ -6,7 +6,5 @@ import { Blueprint } from './Blueprint';

getProfiles(): Array<Blueprint<any, any, any>>;
private resolveFilePaths;
private resolveClasses;
private getImportsFromPath;
private getClasses;
private createFactoryProfileInstance;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils");
var Blueprint_1 = require("./Blueprint");

@@ -10,21 +9,4 @@ var BlueprintLoader = (function () {

BlueprintLoader.prototype.getProfiles = function () {
var files = this.getImportsFromPath(this.fixtureProfiles);
return this.resolveFilePaths(files, []).concat(this.resolveClasses(this.fixtureProfiles));
return this.resolveClasses(this.fixtureProfiles).slice();
};
BlueprintLoader.prototype.resolveFilePaths = function (value, profiles) {
var _this = this;
if (utils_1.isFunction(value) || value instanceof Blueprint_1.Blueprint) {
var instance = this.createFactoryProfileInstance(value);
if (instance) {
profiles.push(instance);
}
}
else if (Array.isArray(value)) {
value.forEach(function (v) { return _this.resolveFilePaths(v, profiles); });
}
else if (typeof value === 'object' && value !== null) {
Object.keys(value).forEach(function (key) { return _this.resolveFilePaths(value[key], profiles); });
}
return profiles;
};
BlueprintLoader.prototype.resolveClasses = function (cls) {

@@ -41,15 +23,2 @@ var _this = this;

};
BlueprintLoader.prototype.getImportsFromPath = function (values) {
var patterns = values.filter(function (v) { return typeof v === 'string'; });
if (patterns.length === 0) {
return [];
}
return patterns
.reduce(function (paths, pattern) {
return paths.concat(utils_1.loadDep('glob').sync(pattern));
}, [])
.map(function (filePath) {
return require(utils_1.loadDep('path').resolve(process.cwd(), filePath));
});
};
BlueprintLoader.prototype.getClasses = function (values) {

@@ -73,2 +42,1 @@ return values.filter(function (v) { return typeof v !== 'string'; });

exports.BlueprintLoader = BlueprintLoader;
//# sourceMappingURL=BlueprintLoader.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=BlueprintOptions.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=DeepEntityPartial.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=EntityObjectType.js.map

@@ -5,2 +5,3 @@ import { Blueprint } from './blueprint/Blueprint';

import { EntityFactoryExecutor } from './EntityFactoryExecutor';
import { EntityFactoryGeneratorMethod } from './EntityFactoryGeneratorMethod';
import { EntityFactoryOptions } from './EntityFactoryOptions';

@@ -15,6 +16,9 @@ import { EntityFactoryRegisterCallback } from './EntityFactoryRegisterCallback';

for<EntityType = any>(entity: string | EntityObjectType<EntityType>): BlueprintBuilder<EntityType>;
gen<Entity = any>(count: EntityFactoryGeneratorMethod<Entity>): Promise<Entity>;
gen<Entity = any>(count: 1, factoryMethod: EntityFactoryGeneratorMethod<Entity>): Promise<Entity>;
gen<Entity = any>(count: number, factoryMethod: EntityFactoryGeneratorMethod<Entity>): Promise<Entity[]>;
hasBlueprint(entity: EntityObjectType<any> | string): boolean;
getProfile(entity: string): Blueprint<Record<string, any>, any, any>;
getProfile<Entity>(entity: string | EntityObjectType<Entity>): Blueprint<Entity, any, any>;
register(fixture: Blueprint<any, any, any> | EntityFactoryRegisterCallback): EntityFactory;
register<Entity>(fixture: Blueprint<Entity, any, any> | EntityFactoryRegisterCallback<Entity>): EntityFactory;
}
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var faker = require("faker");
var ObjectAdapter_1 = require("./adapters/object/ObjectAdapter");

@@ -30,2 +66,32 @@ var Blueprint_1 = require("./blueprint/Blueprint");

};
EntityFactory.prototype.gen = function (count, factoryMethod) {
return __awaiter(this, void 0, void 0, function () {
var generatedObjects, i, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (utils_1.isFunction(count)) {
factoryMethod = count;
count = 1;
}
if (!factoryMethod) return [3, 5];
generatedObjects = [];
i = 0;
_a.label = 1;
case 1:
if (!(i < count)) return [3, 4];
return [4, factoryMethod({ faker: faker, factory: this })];
case 2:
result = _a.sent();
generatedObjects.push(result);
_a.label = 3;
case 3:
i++;
return [3, 1];
case 4: return [2, count === 1 ? generatedObjects[0] : generatedObjects];
case 5: return [2];
}
});
});
};
EntityFactory.prototype.hasBlueprint = function (entity) {

@@ -53,2 +119,1 @@ return this.profiles.has(entity);

exports.EntityFactory = EntityFactory;
//# sourceMappingURL=EntityFactory.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=EntityFactoryExecutor.js.map

@@ -5,3 +5,3 @@ import { Adapter } from './adapters/Adapter';

adapter?: Adapter;
blueprints?: Array<Function | string | Blueprint<any, any, any>>;
blueprints?: Array<Function | Blueprint<any, any, any>>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=EntityFactoryOptions.js.map
import { Blueprint } from './blueprint/Blueprint';
export declare type EntityFactoryRegisterCallback = (blueprint: Blueprint<any, any, any>) => void;
export declare type EntityFactoryRegisterCallback<Entity = Partial<{}>> = (bp: Blueprint<Entity, any, any>) => void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=EntityFactoryRegisterCallback.js.map

@@ -9,4 +9,2 @@ export * from './adapters/Adapter';

export * from './blueprint/BlueprintBuilder';
export * from './blueprint/BlueprintDeepPartial';
export * from './blueprint/BlueprintDeepPartialMethod';
export * from './blueprint/BlueprintDefinitionAfterMethod';

@@ -13,0 +11,0 @@ export * from './blueprint/BlueprintDefinitionAfterMethodContext';

@@ -12,2 +12,1 @@ "use strict";

__export(require("./EntityFactory"));
//# sourceMappingURL=index.js.map
{
"name": "@entity-factory/core",
"version": "0.1.1-alpha.1",
"version": "0.1.2",
"description": "Create entities on the fly for mocking and testing",

@@ -14,6 +14,5 @@ "author": "Jeremy Cloutier",

"dependencies": {
"faker": "^4.1.0",
"glob": "^7.1.3"
"faker": "^4.1.0"
},
"gitHead": "ac39b65738dc3f539cbe988b0f242c04f836a19d"
"gitHead": "765a1245e1fdbb6cee2522a207bd53229b0c5042"
}

@@ -7,2 +7,4 @@ # Entity Factory

[Documentation](https://entity-factory.gitbook.io/entity-factory/)
## Table of Contents

@@ -13,6 +15,2 @@

- [Quick Guide](#quick-guide)
- [Creating an Entity Factory](#creating-an-entity-factory)
- [Defining a Blueprint](#defining-a-blueprint)
- [Using the Builder](#using-the-builder)
- [Using Adapters](#using-adapters)

@@ -23,3 +21,3 @@ ## Features

- Generate objects with nested relations
- Typeorm Support - Generate and Persist Entities and nested relations
- [Typeorm Support](https://github.com/entity-factory/entity-factory/tree/master/packages/typeorm) - Generate and Persist Entities and nested relations

@@ -39,27 +37,36 @@ ## Installation

export const entityFactory = new EntityFactory();
class UserBlueprint extends ObjectBlueprint {
constructor() {
super();
entityFactory.register(bp => {
// Set the key used for identifying an object in the factory.
bp.type('user');
this.type('user');
bp.define(async faker => ({
username: faker.internet.userName(),
email: faker.internet.email(),
active: faker.random.boolean(),
}));
this.define(async ({ faker, factory }) => ({
username: faker.internet.userName(),
email: faker.internet.email(),
active: faker.random.boolean(),
}));
// define a state transform to return a user with embedded posts
bp.state('with-posts', async faker => ({
posts: async factory => factory.for('post').create(2),
}));
});
// define a state transform to return a user with embedded posts
this.state('with-posts', async ({ faker, factory }) => ({
posts: await factory.for('post').create(2),
}));
}
}
entityFactory.register(bp => {
bp.type('post');
class PostBlueprint extends ObjectBlueprint {
constructor() {
super();
bp.define(async faker => ({
title: faker.company.bsBuzz(),
body: faker.lorem.sentences(2),
}));
this.type('post');
this.define(async ({ faker, factory }) => ({
title: faker.company.bsBuzz(),
body: faker.lorem.sentences(2),
}));
}
}
export const entityFactory = new EntityFactory({
blueprints: [UserBlueprint, PostBlueprint],
});

@@ -80,410 +87,9 @@

## Creating an Entity Factory
### factory = new EntityFactory([opts])
```javascript
const entityFactory = new EntityFactory({
adapter: new OjectAdapter()
blueprints: [
'**/*.blueprint.js', // glob pattern
new UserBlueprint(), // blueprint instance
PostBlueprint, // blueprint reference
],
})
```
Create a new entity factory instance. Opts is optional and can contain the
following attributes.
- **opts.adapter (optional)**: default `new ObjectAdapter()`. The adapter is
used when making and creating objects. Available adapters
_ **ObjectAdapter**: Creates standard javascript objects with incrementing
id values.
_ **TypeormAdapter**: Makes and persists TyprORM entities.
- **opts.profiles (optional)**: default `[]`. The profiles array accepts an
array of glob patterns, Profile instances or Profile classes.
_ **glob patterns**: ex: `’src/\*\*/_.profile.js'`. If a glob pattern is passed EntityFactory will attempt to load all profiles found in the path and register them. * **Class Reference**: ex`UserProfile`. If a class reference is passed Entity factory will create a new instance and register it. * **Profile Instance**: Ex`new UserProfile()`. If a profile instance is
provided EntityFactory will register it.
### factory.register(profile | callback(profile))
```javascript
class UserProfile extends ObjectBlueprint {}
// Accepts a reference or an instance to a blueprint
factory.register(UserBlueprint);
factory.register(new PostBlueprint());
// or a callback
factory.register(bp => {
bp.type('user');
bp.define(/*...*/);
});
```
Registers a profile with the factory
- **Arguments**
- **profile**: Must be a profile instance, or a callback method accepting a
profile instance.
- **Returns**: void
### factory.for(key)
```javascript
const users = await factory.for('user').create(3);
const users = await factory.for(User).create(3);
```
- **Arguments**
- **key (string|object reference)**: The is defined in the profile calling
`type(key)` in a blueprint and used to retrieve the profile from the factory
and supply it to the `ProfileBuilder`.
- **Returns**: [BlueprintBuilder]($blueprint-builder)
## Defining a Blueprint
Definging blueprint can be done either via callback to `EntityFactory.register()`
or as a separate Blueprint class.
### Class based definition
Class based blueprint must extend a blueprint class. Each adapter has it's own
blueprint class which provides different available options specific to the
adapter. By default the Object adapter can be used with Entity Factory. For more
information on the options available please refer to the docs for each adapter
blueprint.
- [ObjectBlueprint](#objectblueprint)
- [TypeormBlueprint](#typeormblueprint)
```javascript
// class based Blueprint definition
export class UserBlueprint extends ObjectBlueprint {
constructor() {
super();
this.type('user');
this.define(async faker => {
return {
// user attributes
};
});
}
}
// class based blueprints are passed to entity factory via the constructor
const factory = new EntityFactory({
blueprints: [UserBlueprint],
});
```
### Callback based definition
Registering a blueprint via a callback is an alternative to using a blueprint
class. It does however have it's drawbacks. Using this method will always
return a basic Blueprint class that is not specific to the adapter being used.
As a result any additional functionality provided by the adapters blueprint
will not be available with this method.
```javascript
const factory = new EntityFactory();
factory.register(bp => {
bp.type('user');
bp.define(async faker => {
return {
// user attributes
};
});
});
```
### Blueprint Methods
#### type(string | class) \*Required
Type is used as an identifier within entity factory and can be either a string
or a class reference that is passed. An important thing to note is that the
value passed to `type()` will effect the value returned. Types passed as string
will be created as plain javascript objects. If however a class reference is
provided then Entity factory will attempt to return an instantiated instance of
that class.
**This method must be called**
```typescript
class User {}
blueprint.type(User);
// or
blueprint.type('user');
```
#### options(opts)
Each adapter blueprint can specify different available options. The options are
passed to the adapter at runtime. For adapter blueprint specific options please
refer to their documentation:
- [ObjectBlueprint](#objectblueprint)
- [TypeormBlueprint](#typeormblueprint)
```javascript
blueprint.options({
idAttribute: '_id',
});
```
#### define(callback(faker)) \*Required
Used to create the primary factory method for an entity. The callback method receives a single argument which is a faker instance.
Property values can also an async callback to the factory which will allow data
to be resolved from related factories.
**This method must be called**
```javascript
blueprint.define(faker => {
return {
// faker usage
username: faker.internet.userName(),
// fixed values
active: true,
// async facory callback
posts: async factory => await factory.for('post').create(2),
};
});
```
#### state(string, callback(faker))
Used to override portions of the primary factory method and/or to add additional
properties.
Property values can also an async callback to the factory which will allow data
to be resolved from related factories.
```javascript
blueprint.state('inactive', faker => {
return {
active: false,
};
});
blueprint.state('with-posts', faker => {
return {
// factory callbacks can contain nested factory calls to resolve other
// blueprint instances from the factory.
posts: async factory => factory.for('posts').make(2),
};
});
```
#### After callbacks
- afterMaking(callback(currentEntity, context))
- afterMakingState(string, callback(currentEntity, context))
Fired after a call to `make()` on the builder instance. The entity received will
have been resolved to it's base type but not persisted. The callback will
receive the current entity as well as a context object.
**callback**
- **currentEntity**: resolved entity, plain object or class
- **context**:
- **faker**: faker instance
- **factory**: factory instance
- **adapter**: adapter instance (default ObjectAdapter)
```javascript
// called after calling builder.make()
blueprint.afterMaking(async (user, { faker, factory, adapter }) => {
// manipulate entity
});
// fired after calling builder.make() with an 'active' state transform
blueprint.afterMakingState(
'active',
async (user, { faker, factory, adapter }) => {
// manipulate entity
},
);
```
#### After callbacks
- afterCreating(callback(currentEntity, context))
- afterCreatingState(string, callback(currentEntity, context))
Fired after a call to `create()` on the builder instance. The entity received
will have been resolved and persisted. The callback will receive the current
entity as well as a context object.
**callback**
- **currentEntity**: resolved entity, plain object or class
- **context**:
- **faker**: faker instance
- **factory**: factory instance
- **adapter**: adapter instance (default ObjectAdapter)
```javascript
// called after calling builder.create()
blueprint.afterCreating(async (user, { faker, factory, adapter }) => {
// manipulate entity
});
// fired after calling builder.create() with an 'active' state transform
blueprint.afterCreatingState(
'active',
async (user, { faker, factory, adapter }) => {
// manipulate entity
},
);
```
## Using the Builder
The builder is accessed via an entity factory instance by calling the `for()`
method.
```javascript
factory
.for('user')
.state('active')
.with({
email: 'test@test.com',
})
.create();
```
### Builder Methods
### state(...string)
Used to apply defined state transforms to a factory. The states are applied the order they are provided to the function.
```javascript
factory.for(User).state('active', 'with-posts');
```
### with(partial)
Used for overriding properties on a created entity. This is particularly useful
when testing for a specific value.
```javascript
factory.for(User).with({
name: 'john',
});
```
### make([int, [partial]])
Resolves the partials generated by the factory methods and converts them into
plain objects or class instances. Unlike `create()` the entity will not be
persisted
```javascript
factory.for(User).make();
factory.for(User).make(1);
factory.for(User).make(2);
```
### create([int, [partial]])
Resolves and persists the partials generated by the factory methods and converts
them into plain objects and class instances. Depending on the adapter this can
mean that they simple have an id generated for them or they are saved to teh
database.
```javascript
factory.for(User).create();
factory.for(User).create(1);
factory.for(User).create(2);
```
## Using Adapters
Entity Factory has the ability to use adapters to persist data in various
formats. The ObjectAdapter is included in Entity Factory by default.
**Available Adapters**
- [ObjectAdapter](#object-adapter-usage)
- [TypeormAdapter](https://github.com/entity-factory/entity-factory/tree/master/packages/typeorm)
### Object Adapter Usage
The ObjectAdapter is used for creating mock data as plain javascript objects.
It will generate sequential id's for objects to simulate data coming from a
database.
### ObjectAdapter([opts])
```javascript
const objectAdapter = new new ObjectAdapter()
// or
const objectAdapter = new ObjectAdaper({
generateId: true;
defaultIdAttribute: 'id';
});
const factory = new EntityFactory({
adapter: objectAdapter,
})
```
- **opts**: optional
- **generateId**: default **true**, used to enable or disable id generation
by default. This can be overriden at the blueprint level.
- **defaultIdAttribute**: default **id**, sets the default name of the id
attribute that entity factory will generate if generateId is true.
### Object Blueprint
**Available Options**
- **generateId**: overrides the default adapter setting for a particular entity.
- **idAttribute**: overrides the adapter setting to change the genrated id
attribute name.
```javascript
export class WidgetBlueprint extends ObjectBlueprint {
constructor() {
super();
this.type(Widget);
this.options({
generateId: true
idAttribute: '_id';
})
}
}
```
## TODO
- [ ] imporove docs
- [ ] resolve nested objects
- [x] imporove docs
- [x] resolve nested objects
- [ ] resolve nested array
- [ ] allow guid id's for object adapter
- [ ] add method to generate random objects on the fly without a blueprint
- [x] add method to generate random objects on the fly without a blueprint
definition
export declare const getName: (entity: any) => string;
export declare const isFunction: (functionToCheck: any) => boolean;
export declare const loadDep: (type: string) => any;

@@ -11,12 +11,1 @@ "use strict";

};
exports.loadDep = function (type) {
switch (type) {
case 'glob':
return require('glob');
case 'path':
return require('path');
default:
return;
}
};
//# sourceMappingURL=index.js.map
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc