Skip to content

Commit

Permalink
fix relative imports
Browse files Browse the repository at this point in the history
  • Loading branch information
cice committed Mar 30, 2020
1 parent dc6bed8 commit 6a29923
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type GetResponse = {
export type GetUsersResponse = {
id?: number;
name: string;
}[];
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { HttpClient } from '@angular/common/http';
import { HttpResponse } from '@angular/common/http';
import { Inject } from '@angular/core';
import { Injectable } from '@angular/core';
import { API_HOST } from './api-host';
import { GetResponse } from './users/get-response';
import { API_HOST } from '../api-host';
import { GetUsersResponse } from './get-users.response';
@Injectable()
export class UsersGateway {
constructor(private readonly _httpClient: HttpClient, @Inject(API_HOST) private readonly _apiHost: string) {}

get(options?: Parameters<HttpClient['request']>[2]): Observable<HttpResponse<GetResponse>> {
return this._httpClient.request('get', '/users', options);
getUsers(options?: Parameters<HttpClient['request']>[2]): Observable<HttpResponse<GetUsersResponse>> {
return this._httpClient.request('getUsers', '/users', options);
}
}
24 changes: 24 additions & 0 deletions examples/generated/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"include": [
"**/*.ts"
],

"compilerOptions": {
"experimentalDecorators": true,
"strict": true,
"target": "es2015",
"module": "CommonJS",
"moduleResolution": "node",
"outDir": "dist",
"declaration": true,
"typeRoots": [
"../../node_modules/@types"
],
"lib": [
"ES2015"
],
"types": [
"node"
]
}
}
8 changes: 4 additions & 4 deletions src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ export function httpVerbAndHrefBasedMethodName(
const prefix = method.toLocaleLowerCase();
const localHref = stripCommonPath(href, commonHref);

return [prefix, ...pathToCapitalizedNameParts(localHref)].join();
return [prefix, ...pathToCapitalizedNameParts(localHref)].join('');
}

export function commonHrefBasedClassName(resource: HyperSchemaResource4): string {
const commonHref = getCommonHref(resource);
const typeName = pathToCapitalizedNameParts(commonHref).join();
const typeName = pathToCapitalizedNameParts(commonHref).join('');
if (typeName === '') {
throw `can't build type-name for href ${commonHref}`;
}
Expand Down Expand Up @@ -78,7 +78,7 @@ export function methodNameBasedQueryParamsTypeName(
}

export function kebapizedClassName(nameOfClass: string): string {
return paramCase(nameOfClass);
return paramCase(nameOfClass).replace(/-(gateway|response|request)/, '.$1');
}

export function allInRoot(generated: GeneratedCode): string[] {
Expand All @@ -91,7 +91,7 @@ export function scopeByResource(generated: GeneratedCode): string[] {
return [];
case 'transfer-object':
case 'gateway':
return [kebapizedClassName(commonHrefBasedClassName(generated.source.resource)).replace('-gateway', '')];
return [kebapizedClassName(commonHrefBasedClassName(generated.source.resource)).replace('.gateway', '')];
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/generators/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {compile, Options} from 'json-schema-to-typescript';
import {GeneratorOptions} from '../options';
import {GatewayClass, GatewayOperation, ResponseTypeDescriptor} from '../type-model';
import {relativePath} from '../util/paths';

export interface GeneratedType {
readonly dependencies: Dependency[];
Expand Down Expand Up @@ -65,10 +66,11 @@ export function getImport(options: GeneratorOptions, dependency: Dependency, tar
return [dependency.name, dependency.source];
case 'code':
case 'transfer-object':
const path = options.getTargetPath(dependency);
const localPath = targetPath.join('/');
const fileName = options.buildFileName(dependency.nameOfClass);
const fullPath = ['.', ...path, fileName].join('/');
// TODO: relativize
const dependencyPath = [...options.getTargetPath(dependency), fileName].join('/');
let fullPath = relativePath(localPath, dependencyPath);

return [dependency.nameOfClass, fullPath];
}
}
Expand Down
14 changes: 8 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import {defaultOptions} from './defaults';
import {
Dependency,
generateApiHostInjectionToken,
GeneratedAdditional, GeneratedCode,
GeneratedGatewayClass,
GeneratedCode,
GeneratedType,
generateGatewayTypeSource,
generateImports,
Expand Down Expand Up @@ -108,19 +107,22 @@ export async function generateGateways(
generatedClasses.push(gatewayTypeDef);

for (let operation of gatewayClass.operations) {
if(operation.response) {
if (operation.response) {
const responseTypeDef = await generateResponseType(operation.response, options.json2ts);
generatedClasses.push(responseTypeDef);
gatewayTypeDef.dependencies.push(responseTypeDef);
}
}
}


return Array.from(buildFileSet(options, generatedClasses));
}

export function generateAllImports(options: GeneratorOptions, dependencies: Dependency[], targetPath: string[]): string {
export function generateAllImports(
options: GeneratorOptions,
dependencies: Dependency[],
targetPath: string[],
): string {
return generateImports(
dependencies.map((dep) => getImport(options, dep, targetPath)),
);
Expand All @@ -147,6 +149,6 @@ export function* buildFileSet(
path: targetPath,
name: options.buildFileName(gateway.nameOfClass),
content: combine(options, gateway, targetPath),
}
};
}
}
16 changes: 14 additions & 2 deletions src/util/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,21 @@ export function getCommonPath(paths: string[]) {
}

export function stripCommonPath(path: string, commonPath: string): string {
if(path.startsWith(commonPath)) {
return path.slice(commonPath.length);
if(path.startsWith(commonPath + '/')) {
return path.slice(commonPath.length + 1);
}

return path;
}


export function relativePath(from: string, to: string): string {
from = from + '/';
const commonPath = getCommonPath([from, to]);
const fromLevel = stripCommonPath(from, commonPath).split('/').length - 1;
const dives = Array(fromLevel).fill('..');
to = [...dives, stripCommonPath(to, commonPath)].join('/');


return to.startsWith('../') ? to : './' + to;
}
38 changes: 36 additions & 2 deletions test/unit/util/paths.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {getCommonPath, stripCommonPath} from '../../../src/util/paths';
import {getCommonPath, relativePath, stripCommonPath} from '../../../src/util/paths';

describe('getCommonPath', () => {
test('simple case', () => {
Expand Down Expand Up @@ -43,7 +43,41 @@ describe('stripCommonPath', () => {
test('simple case', () => {
const stripped = stripCommonPath('/foo/bar/blub', '/foo/bar');

expect(stripped).toEqual('/blub');
expect(stripped).toEqual('blub');
});
});

describe('relativePath', () => {
test('root', () => {
const result = relativePath(
'faa',
'bum'
);

expect(result).toEqual('../bum')
});
test('unrelated', () => {
const result = relativePath(
'faa',
'foo/baz/bum'
);

expect(result).toEqual('../foo/baz/bum')
});
test('nephew', () => {
const result = relativePath(
'foo',
'foo/baz/bum'
);

expect(result).toEqual('./baz/bum')
});
test('siblings', () => {
const result = relativePath(
'foo',
'foo/baz'
);

expect(result).toEqual('./baz')
});
});

0 comments on commit 6a29923

Please sign in to comment.