Skip to content

Commit

Permalink
fix: minor enhancements for path replacing + enhanced find operation
Browse files Browse the repository at this point in the history
  • Loading branch information
tada5hi committed Feb 16, 2023
1 parent 2f1a52f commit 17160ea
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 57 deletions.
18 changes: 9 additions & 9 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,21 @@ The following commands are available in the terminal:
- `typeorm-extension db:drop` to drop the database
- `typeorm-extension seed` seed the database

If the application has not yet been built or is to be tested with ts-node, the commands can be adapted as follows:

```
"scripts": {
...
"db:create": "typeorm-extension db:create",
"db:drop": "typeorm-extension db:drop",
"seed": "typeorm-extension seed"
...
"db:create": "ts-node ./node_modules/typeorm-extension/dist/cli/index.js db:create",
"db:drop": "ts-node ./node_modules/typeorm-extension/dist/cli/index.js db:drop",
"seed": "ts-node ./node_modules/typeorm-extension/dist/cli/index.js seed"
}
```

Ts-node is no longer needed due to the fact that TypeScript files are transpiled on the file as needed.
The same applies to files from another module system (CJS / ESM) 🧙‍.
It is also possible to use files (seeder,factories,entities,migrations,...) from another module system (CJS/ESM),
as they will be transpiled if necessary 🧙.

> Read the [Seeding Configuration](#configuration) section to find out how to specify the path,
> for the seeder- & factory-location.
Read the [Seeding Configuration](#configuration) section to find out how to specify the path,
for the seeder- & factory-location.

#### Options

Expand Down
59 changes: 26 additions & 33 deletions src/data-source/find/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { DataSource, InstanceChecker } from 'typeorm';
import { DataSourceFindOptions } from './type';
import { hasOwnProperty, isTsNodeRuntimeEnvironment } from '../../utils';
import { readTsConfig } from '../../utils/tsconfig';
import { changeTSToJSPath } from '../options';
import { changeTSToJSPath, safeReplaceWindowsSeparator } from '../options';

export async function findDataSource(
context?: DataSourceFindOptions,
Expand All @@ -31,23 +31,26 @@ export async function findDataSource(
}
}

const basePaths = [
process.cwd(),
];

if (
context.directory &&
context.directory !== process.cwd()
) {
context.directory = path.isAbsolute(context.directory) ?
context.directory :
path.join(process.cwd(), context.directory);

basePaths.unshift(context.directory);
let { directory } = context;
let directoryIsPattern = false;
if (context.directory) {
if (path.isAbsolute(context.directory)) {
directory = context.directory;
} else {
directoryIsPattern = true;
directory = safeReplaceWindowsSeparator(context.directory);
}
}

const lookupPaths = [];
for (let j = 0; j < files.length; j++) {
if (
directory &&
directoryIsPattern
) {
lookupPaths.push(path.posix.join(directory, files[j]));
}

lookupPaths.push(...[
path.posix.join('src', files[j]),
path.posix.join('src/{db,database}', files[j]),
Expand All @@ -57,32 +60,22 @@ export async function findDataSource(
files.push(...lookupPaths);

if (!isTsNodeRuntimeEnvironment()) {
let tsConfigFound = false;
const { compilerOptions } = await readTsConfig();
const outDir = compilerOptions ? compilerOptions.outDir : undefined;

for (let i = 0; i < basePaths.length; i++) {
const { compilerOptions } = await readTsConfig(basePaths[i]);
if (compilerOptions) {
for (let j = 0; j < files.length; j++) {
files[j] = changeTSToJSPath(files[j], compilerOptions.outDir);
}

tsConfigFound = true;
break;
}
}

if (!tsConfigFound) {
for (let j = 0; j < files.length; j++) {
files[j] = changeTSToJSPath(files[j]);
}
for (let j = 0; j < files.length; j++) {
files[j] = changeTSToJSPath(files[j], outDir);
}
}

for (let i = 0; i < files.length; i++) {
const info = await locate(
`${files[i]}.{ts,cts,mts,js,cjs,mjs}`,
`${files[i]}.{js,cjs,mjs,ts,cts,mts}`,
{
path: basePaths,
path: [
process.cwd(),
...(directory && !directoryIsPattern ? [directory] : []),
],
ignore: ['**/*.d.ts'],
},
);
Expand Down
42 changes: 32 additions & 10 deletions src/data-source/options/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ const stripLeadingModifier = (text: string) => {
return text;
};

export function safeReplaceWindowsSeparator(input: string) {
if (
input.indexOf('*') !== -1 ||
input.indexOf('**') !== -1 ||
input.indexOf('{') !== -1
) {
return input;
}

return input.replace(/\\/g, '/');
}

export function changeTSToJSPath(
input: string,
dist?: string,
Expand All @@ -26,21 +38,23 @@ export function changeTSToJSPath(
base = base.substring(baseIndex + 1);
}

// if the path already contains a js file extension, we are done
const jsExtensions = ['js', 'cjs', 'mjs'];
for (let i = 0; i < jsExtensions.length; i++) {
if (base.indexOf(jsExtensions[i]) !== -1) {
return input;
}
}

if (src) {
src = withoutTrailingSlash(stripLeadingModifier(src));
src = withoutTrailingSlash(
stripLeadingModifier(
safeReplaceWindowsSeparator(src),
),
);
}
src = src || 'src';

if (dist) {
dist = withoutTrailingSlash(stripLeadingModifier(dist));
dist = withoutTrailingSlash(
stripLeadingModifier(
safeReplaceWindowsSeparator(
dist,
),
),
);
}
dist = dist || 'dist';

Expand All @@ -59,6 +73,14 @@ export function changeTSToJSPath(
}
}

// if the path already contains a js file extension, we are done
const jsExtensions = ['js', 'cjs', 'mjs'];
for (let i = 0; i < jsExtensions.length; i++) {
if (base.indexOf(jsExtensions[i]) !== -1) {
return input;
}
}

const tsExtensions = ['ts', 'cts', 'mts'];
for (let i = 0; i < tsExtensions.length; i++) {
const baseExtensionIndex = base.indexOf(tsExtensions[i]);
Expand Down
2 changes: 1 addition & 1 deletion src/seeder/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { DataSource } from 'typeorm';
import { SeederFactoryConfig, SeederFactoryManager } from './factory';

export interface Seeder {
run(dataSource: DataSource, factoryManager: SeederFactoryManager) : Promise<unknown>;
run(dataSource: DataSource, factoryManager: SeederFactoryManager) : Promise<any>;
}

export type SeederConstructor = new () => Seeder;
Expand Down
35 changes: 31 additions & 4 deletions test/unit/data-source/find.spec.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,54 @@
import {InstanceChecker} from "typeorm";
import {findDataSource} from "../../../src";
import path from "path";

describe('src/data-source/utils/find.ts', () => {
it('should find data-source', async () => {
const dataSource = await findDataSource({
let dataSource = await findDataSource({
directory: path.join(__dirname, '..', '..', 'data', 'typeorm')
});

expect(dataSource).toBeDefined();
expect(InstanceChecker.isDataSource(dataSource));
if(dataSource) {
expect(dataSource.options).toBeDefined();
expect(dataSource.options.extra).toBeDefined();
}

dataSource = await findDataSource({
directory: 'test/data/typeorm'
})

expect(dataSource).toBeDefined();
expect(InstanceChecker.isDataSource(dataSource));
});

it('should find data-source with windows separator', async () => {
const dataSource = await findDataSource({
directory: 'test\\data\\typeorm'
})

expect(dataSource).toBeDefined();
expect(InstanceChecker.isDataSource(dataSource));
})

it('should find data-source with default export', async () => {
const dataSource = await findDataSource({
let dataSource = await findDataSource({
fileName: 'data-source-default',
directory: path.join(__dirname, '..', '..', 'data', 'typeorm')
});

expect(dataSource).toBeDefined();
expect(InstanceChecker.isDataSource(dataSource));
if(dataSource) {
expect(dataSource.options).toBeDefined();
expect(dataSource.options.extra).toBeUndefined();
}

dataSource = await findDataSource({
fileName: 'data-source-default',
directory: 'test/data/typeorm'
})

expect(dataSource).toBeDefined();
expect(InstanceChecker.isDataSource(dataSource));
})
})

0 comments on commit 17160ea

Please sign in to comment.