Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: map async and map array async #537

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 142 additions & 42 deletions packages/core/src/lib/core.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
import { mapMutate, mapReturn } from './mappings/map';
import {
CUSTOM_NODE_INSPECT,
ERROR_HANDLER,
MAPPINGS,
METADATA_MAP,
METADATA_OBJECT_MAP,
NAMING_CONVENTIONS,
PROFILE_CONFIGURATION_CONTEXT,
RECURSIVE_COUNT,
RECURSIVE_DEPTH,
STRATEGY,
CUSTOM_NODE_INSPECT,
ERROR_HANDLER,
MAPPINGS,
METADATA_MAP,
METADATA_OBJECT_MAP,
NAMING_CONVENTIONS,
PROFILE_CONFIGURATION_CONTEXT,
RECURSIVE_COUNT,
RECURSIVE_DEPTH,
STRATEGY
} from './symbols';
import type {
ArrayKeyedMap,
Dictionary,
ErrorHandler,
MapOptions,
Mapper,
Mapping,
MappingConfiguration,
MappingStrategy,
MappingStrategyInitializer,
Metadata,
MetadataIdentifier,
ModelIdentifier,
NamingConventionInput,
import {
ArrayKeyedMap,
Dictionary,
ErrorHandler,
MapOptions,
Mapper,
Mapping,
MappingConfiguration,
MappingStrategy,
MappingStrategyInitializer,
Metadata,
MetadataIdentifier,
ModelIdentifier,
NamingConventionInput
} from './types';
import { mapAsyncHandler } from './utils/async-map-handler';
import { getMapping } from './utils/get-mapping';
import { AutoMapperLogger } from './utils/logger';

Expand Down Expand Up @@ -274,14 +275,42 @@ Mapper {} is an empty Object as a Proxy. The following methods are available to
| MapOptions<TSource, TDestination>,
options?: MapOptions<TSource, TDestination>
): Promise<TDestination> => {
const result = receiver['map'](
const mapped = receiver['map'](
sourceObject,
sourceIdentifier,
destinationIdentifierOrOptions,
options
);
return new Promise((res) => {
setTimeout(res, 0, result);

// start get mappings
const { destinationIdentifier, mapOptions } =
getOptions(
sourceIdentifier,
destinationIdentifierOrOptions,
options
);

const mapping = getMapping(
receiver,
sourceIdentifier,
destinationIdentifier
);
//
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably a forgotten comment 👀


return new Promise((resolve, reject) => {
mapAsyncHandler(
mapping,
sourceObject,
destinationIdentifier,
mapOptions || {},
mapped
)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
});
};
}
Expand Down Expand Up @@ -380,15 +409,41 @@ Mapper {} is an empty Object as a Proxy. The following methods are available to
| MapOptions<TSource[], TDestination[]>,
options?: MapOptions<TSource[], TDestination[]>
) => {
const result = receiver['mapArray'](
const mapped = receiver['mapArray'](
sourceArray,
sourceIdentifier,
destinationIdentifierOrOptions,
options
);
return new Promise((res) => {
setTimeout(res, 0, result);
});
const { destinationIdentifier, mapOptions } =
getOptions(
sourceIdentifier,
destinationIdentifierOrOptions,
options
);

const mapping = getMapping(
receiver,
sourceIdentifier,
destinationIdentifier
);

return Promise.all(
mapped.map(
async (
sourceObject: TDestination,
i: number
) => {
return mapAsyncHandler(
mapping,
sourceArray[i],
destinationIdentifier,
mapOptions || {},
sourceObject
);
}
)
);
};
}

Expand Down Expand Up @@ -449,16 +504,42 @@ Mapper {} is an empty Object as a Proxy. The following methods are available to
| MapOptions<TSource, TDestination>,
options?: MapOptions<TSource, TDestination>
) => {
return new Promise((res) => {
receiver['mutate'](
sourceObject,
destinationObject,
//
receiver['mutate'](
sourceObject,
destinationObject,
sourceIdentifier,
destinationIdentifierOrOptions,
options
);

// start get mappings
const { destinationIdentifier, mapOptions } =
getOptions(
sourceIdentifier,
destinationIdentifierOrOptions,
options
);

setTimeout(res, 0);
const mapping = getMapping(
receiver,
sourceIdentifier,
destinationIdentifier
);

return new Promise<void>((resolve, reject) => {
mapAsyncHandler(
mapping,
sourceObject,
destinationIdentifier,
mapOptions || {}
)
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
};
}
Expand Down Expand Up @@ -552,17 +633,36 @@ Mapper {} is an empty Object as a Proxy. The following methods are available to
| MapOptions<TSource[], TDestination[]>,
options?: MapOptions<TSource[], TDestination[]>
) => {
return new Promise((res) => {
receiver['mutateArray'](
sourceArray,
destinationArray,
receiver['mutateArray'](
sourceArray,
destinationArray,
sourceIdentifier,
destinationIdentifierOrOptions,
options
);
const { destinationIdentifier, mapOptions } =
getOptions(
sourceIdentifier,
destinationIdentifierOrOptions,
options
);

setTimeout(res, 0);
});
const mapping = getMapping(
receiver,
sourceIdentifier,
destinationIdentifier
);

return Promise.all(
sourceArray.map(async (sourceObject) => {
mapAsyncHandler(
mapping,
sourceObject,
destinationIdentifier,
mapOptions || {}
);
})
);
};
}

Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ export interface Converter<
convert(source: TSource): TConvertDestination;
}

export type MapCallbackAsync<
TSource extends Dictionary<TSource>,
TDestination extends Dictionary<TDestination>,
TExtraArgs extends Record<string, any> = Record<string, any>
> = (
source: TSource,
destination: TDestination,
extraArguments?: TExtraArgs
) => Promise<void>;

export type MapCallback<
TSource extends Dictionary<TSource>,
TDestination extends Dictionary<TDestination>,
Expand Down
31 changes: 31 additions & 0 deletions packages/core/src/lib/utils/async-map-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Dictionary } from '@mikro-orm/core';
import { MapCallbackAsync, Mapping } from '../types';

export async function mapAsyncHandler<
TSource extends Dictionary<TSource>,
TDestination extends Dictionary<TDestination>,
TExtraArgs extends Record<string, any> = Record<string, any>
>(
mapping: Mapping<TSource, TDestination>,
source: TSource,
destination: TDestination,
extraArguments: TExtraArgs,
mapped?: TDestination
) {
if (!mapping[7]) {
mapping[7] = [];
}
const afterMap = mapping[7][1] as MapCallbackAsync<
TSource,
TDestination,
TExtraArgs
>;
if (afterMap) {
await afterMap(source, destination, extraArguments);
}
if (mapped) {
return Object.assign(mapped, destination);
} else {
return destination;
}
}
44 changes: 34 additions & 10 deletions packages/integration-test/src/classes/map-async.spec.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,60 @@
import { classes } from '@automapper/classes';
import {
afterMap,
createMap,
createMapper,
forMember,
ignore,
afterMap,
createMap,
createMapper,
forMember,
ignore
} from '@automapper/core';
import { SimpleUserDto } from './dtos/simple-user.dto';
import { SimpleUser } from './models/simple-user';

describe('Map Async Classes', () => {
const mapper = createMapper({ strategyInitializer: classes() });

it('should map', async () => {
it('should map a single', async () => {
createMap(
mapper,
SimpleUser,
SimpleUserDto,
forMember((d) => d.fullName, ignore()),
afterMap(async (_, destination) => {
const fullName = await Promise.resolve().then(
() => 'Tran Chau'
);
const fullName = await new Promise((resolve) => {
setTimeout(() => {
resolve('Tran Chau');
}, 1000);
});
Object.assign(destination, { fullName });
})
);

const dto = await mapper.mapAsync(
new SimpleUser('Chau', 'Tran'),
SimpleUser,
SimpleUserDto
);
expect(dto.fullName).toEqual('Tran Chau');
});

it('should map an array', async () => {
createMap(
mapper,
SimpleUser,
SimpleUserDto,
forMember((d) => d.fullName, ignore()),
afterMap(async (_, destination) => {
const fullName = await new Promise<string>((resolve) => {
setTimeout(() => {
resolve('Tran Chau');
}, 1000);
});
destination.fullName = fullName;
})
);
const dtos = await mapper.mapArrayAsync(
[new SimpleUser('Chau', 'Tran')],
SimpleUser,
SimpleUserDto
);
expect(dtos[0].fullName).toEqual('Tran Chau');
});
});