Skip to content

Commit

Permalink
refactor(repl): extract utility from repl main file
Browse files Browse the repository at this point in the history
  • Loading branch information
micalevisk committed Jun 14, 2022
1 parent 2c4aa9f commit 1cc12ac
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 11 deletions.
14 changes: 14 additions & 0 deletions packages/core/repl/assign-to-object.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Similar to `Object.assign` but copying properties descriptors from `source`
* as well.
*/
export function assignToObject<T, U>(target: T, source: U): T & U {
Object.defineProperties(
target,
Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, Object.create(null)),
);
return target as T & U;
}
13 changes: 2 additions & 11 deletions packages/core/repl/repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,7 @@ import { NestFactory } from '../nest-factory';
import { REPL_INITIALIZED_MESSAGE } from './constants';
import { ReplContext } from './repl-context';
import { ReplLogger } from './repl-logger';

function copyInto(target, source): void {
Object.defineProperties(
target,
Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, Object.create(null)),
);
}
import { assignToObject } from './assign-to-object.util';

export async function repl(module: Type) {
const app = await NestFactory.create(module, {
Expand All @@ -30,7 +21,7 @@ export async function repl(module: Type) {
prompt: clc.green('> '),
ignoreUndefined: true,
});
copyInto(replServer.context, replContext.globalScope);
assignToObject(replServer.context, replContext.globalScope);

return replServer;
}
36 changes: 36 additions & 0 deletions packages/core/test/repl/assign-to-object.util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect } from 'chai';
import { assignToObject } from '@nestjs/core/repl/assign-to-object.util';

describe('assignToObject', () => {
it('should copy all enumerable properties and their descriptors', () => {
const sourceObj = {};
Object.defineProperty(sourceObj, 'foo', {
value: 123,
configurable: true,
enumerable: true,
writable: true,
});
Object.defineProperty(sourceObj, 'bar', {
value: 456,
configurable: true,
enumerable: true,
writable: false,
});
const targetObj = {};

assignToObject(targetObj, sourceObj);

expect(Object.getOwnPropertyDescriptor(targetObj, 'foo')).to.be.eql({
value: 123,
configurable: true,
enumerable: true,
writable: true,
});
expect(Object.getOwnPropertyDescriptor(targetObj, 'bar')).to.be.eql({
value: 456,
configurable: true,
enumerable: true,
writable: false,
});
});
});

0 comments on commit 1cc12ac

Please sign in to comment.