Browse Source

Fix api version parameter in Angular and jQuery proxies

pull/26247/head
maliming 1 month ago
parent
commit
f077249fee
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 59
      framework/src/Volo.Abp.Http/Volo/Abp/Http/ProxyScripting/Generators/JQuery/JQueryProxyScriptGenerator.cs
  2. 9
      framework/src/Volo.Abp.Http/Volo/Abp/Http/ProxyScripting/Generators/ProxyScriptingHelper.cs
  3. 196
      framework/test/Volo.Abp.Http.Tests/Volo/Abp/Http/ProxyScripting/Generators/JQuery/JQueryProxyScriptGenerator_ApiVersion_Tests.cs
  4. 423
      npm/ng-packs/packages/schematics/src/tests/api-version-parameter.spec.ts
  5. 33
      npm/ng-packs/packages/schematics/src/utils/service.ts

59
framework/src/Volo.Abp.Http/Volo/Abp/Http/ProxyScripting/Generators/JQuery/JQueryProxyScriptGenerator.cs

@ -111,29 +111,30 @@ public class JQueryProxyScriptGenerator : IProxyScriptGenerator, ITransientDepen
var versionParam = action.Parameters.FirstOrDefault(p => p.Name == "apiVersion" && p.BindingSourceId == ParameterBindingSources.Path) ??
action.Parameters.FirstOrDefault(p => p.Name == "api-version" && p.BindingSourceId == ParameterBindingSources.Query);
var urlParameters = action.Parameters;
if (versionParam != null)
{
var version = FindBestApiVersion(action);
if (parameterList.Contains("api_version"))
var versionVariable = ProxyScriptingJsFuncHelper.GetParamNameInJsFunc(versionParam);
if (versionParam.Name == versionParam.NameOnMethod)
{
script.AppendLine($" var {ProxyScriptingJsFuncHelper.NormalizeJsVariableName(versionParam.Name)} = api_version ? api_version : '{version}';");
script.AppendLine($" {versionVariable} = {versionVariable} ? {versionVariable} : '{version}';");
}
else
{
var apiVersion = action.Parameters.FirstOrDefault(p =>
p.BindingSourceId.IsIn(ParameterBindingSources.ModelBinding, ParameterBindingSources.Query) &&
p.Name == "api-version");
if (apiVersion != null && parameterList.Contains(apiVersion.NameOnMethod))
{
var apiVersionVariable = ProxyScriptingJsFuncHelper.GetParamNameInJsFunc(apiVersion);
script.AppendLine($" {apiVersionVariable} = {apiVersionVariable} ? {apiVersionVariable} : '{version}';");
}
// The version is read from the input DTO here, so the default goes to a local container
// to keep the caller's object (which may be a FormData) and the other arguments unchanged.
var container = GetUniqueJsVariableName(action, "apiVersionContainer");
var localVersionParam = CreateLocalVersionParameter(versionParam, container);
var versionProperty = ProxyScriptingJsFuncHelper.GetParamNameInJsFunc(localVersionParam).Substring(container.Length + 1);
script.AppendLine($" var {container} = {{ {versionProperty}: {versionVariable} ? {versionVariable} : '{version}' }};");
urlParameters = action.Parameters.Select(p => p == versionParam ? localVersionParam : p).ToList();
}
}
script.AppendLine(" return abp.ajax($.extend(true, {");
AddAjaxCallParameters(script, action);
AddAjaxCallParameters(script, action, urlParameters);
var hasFormFile = action.Parameters.Any(x => x.BindingSourceId == ParameterBindingSources.FormFile);
var ajaxParamsIsFromForm = !hasFormFile && action.Parameters.Any(x => x.BindingSourceId == ParameterBindingSources.Form);
@ -193,6 +194,38 @@ public class JQueryProxyScriptGenerator : IProxyScriptGenerator, ITransientDepen
return (semi < 0 ? mediaType : mediaType.Substring(0, semi)).Trim().ToLowerInvariant();
}
private static string GetUniqueJsVariableName(ActionApiDescriptionModel action, string name)
{
var usedNames = new HashSet<string>(action.Parameters
.Select(p => ProxyScriptingJsFuncHelper.NormalizeJsVariableName(p.NameOnMethod.ToCamelCase())))
{
"ajaxParams"
};
while (usedNames.Contains(name))
{
name += "_";
}
return name;
}
private static ParameterApiDescriptionModel CreateLocalVersionParameter(ParameterApiDescriptionModel versionParam, string container)
{
return new ParameterApiDescriptionModel
{
Name = versionParam.Name,
NameOnMethod = container,
JsonName = versionParam.JsonName,
Type = versionParam.Type,
TypeSimple = versionParam.TypeSimple,
IsOptional = versionParam.IsOptional,
DefaultValue = versionParam.DefaultValue,
ConstraintTypes = versionParam.ConstraintTypes,
BindingSourceId = versionParam.BindingSourceId
};
}
private static string FindBestApiVersion(ActionApiDescriptionModel action)
{
//var configuredVersion = GetConfiguredApiVersion(); //TODO: Implement
@ -211,11 +244,11 @@ public class JQueryProxyScriptGenerator : IProxyScriptGenerator, ITransientDepen
return action.SupportedVersions.Last(); //TODO: Ensure to get the latest version!
}
private static void AddAjaxCallParameters(StringBuilder script, ActionApiDescriptionModel action)
private static void AddAjaxCallParameters(StringBuilder script, ActionApiDescriptionModel action, IList<ParameterApiDescriptionModel> urlParameters)
{
var httpMethod = action.HttpMethod?.ToUpperInvariant() ?? "POST";
script.AppendLine(" url: abp.appPath + '" + ProxyScriptingHelper.GenerateUrlWithParameters(action) + "',");
script.AppendLine(" url: abp.appPath + '" + ProxyScriptingHelper.GenerateUrlWithParameters(action, urlParameters) + "',");
script.Append(" type: '" + httpMethod + "'");
if (action.ReturnValue.Type == typeof(void).FullName)

9
framework/src/Volo.Abp.Http/Volo/Abp/Http/ProxyScripting/Generators/ProxyScriptingHelper.cs

@ -12,6 +12,11 @@ internal static class ProxyScriptingHelper
public const string DefaultHttpVerb = "POST";
public static string GenerateUrlWithParameters(ActionApiDescriptionModel action)
{
return GenerateUrlWithParameters(action, action.Parameters);
}
public static string GenerateUrlWithParameters(ActionApiDescriptionModel action, IList<ParameterApiDescriptionModel> parameters)
{
// The ASP.NET Core route value provider and query string value provider:
// Treat values as invariant culture.
@ -19,8 +24,8 @@ internal static class ProxyScriptingHelper
using (CultureHelper.Use(CultureInfo.InvariantCulture))
{
//TODO: Can be optimized using StringBuilder?
var url = ReplacePathVariables(action.Url, action.Parameters);
url = AddQueryStringParameters(url, action.Parameters);
var url = ReplacePathVariables(action.Url, parameters);
url = AddQueryStringParameters(url, parameters);
return url;
}
}

196
framework/test/Volo.Abp.Http.Tests/Volo/Abp/Http/ProxyScripting/Generators/JQuery/JQueryProxyScriptGenerator_ApiVersion_Tests.cs

@ -0,0 +1,196 @@
#nullable enable
using System.Collections.Generic;
using Shouldly;
using Volo.Abp.Http.Modeling;
using Xunit;
namespace Volo.Abp.Http.ProxyScripting.Generators.JQuery;
public class JQueryProxyScriptGenerator_ApiVersion_Tests
{
private readonly JQueryProxyScriptGenerator _generator = new(
Microsoft.Extensions.Options.Options.Create(new DynamicJavaScriptProxyOptions()));
[Fact]
public void Should_Default_Query_String_Version_Of_Simple_Parameters()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book/{id}",
("id", "id", ParameterBindingSources.Path),
("api-version", "api-version", ParameterBindingSources.Query)));
script.ShouldContain("function(id, api_version, ajaxParams)");
script.ShouldContain("api_version = api_version ? api_version : '2.0';");
script.ShouldContain("{ name: 'api-version', value: api_version }");
}
[Fact]
public void Should_Default_Query_String_Version_Of_Input_Dto()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book",
("Filter", "input", ParameterBindingSources.ModelBinding),
("api-version", "input", ParameterBindingSources.Query)));
script.ShouldContain("function(input, ajaxParams)");
script.ShouldContain("var apiVersionContainer = { api_version: input.api_version ? input.api_version : '2.0' };");
script.ShouldContain("{ name: 'api-version', value: apiVersionContainer.api_version }");
script.ShouldNotContain("input.api_version =");
script.ShouldNotContain("input = ");
}
[Fact]
public void Should_Default_Url_Segment_Version_Of_Simple_Parameters()
{
var script = _generator.CreateScript(BuildAppModel("api/v{apiVersion}/book/{id}",
("id", "id", ParameterBindingSources.Path),
("apiVersion", "apiVersion", ParameterBindingSources.Path)));
script.ShouldContain("function(id, apiVersion, ajaxParams)");
script.ShouldContain("apiVersion = apiVersion ? apiVersion : '2.0';");
script.ShouldContain("'api/v' + apiVersion + '/book/' + id");
}
[Fact]
public void Should_Default_Url_Segment_Version_Of_Input_Dto()
{
var script = _generator.CreateScript(BuildAppModel("api/v{apiVersion}/book",
("Filter", "input", ParameterBindingSources.Query),
("apiVersion", "input", ParameterBindingSources.Path)));
script.ShouldContain("function(input, ajaxParams)");
script.ShouldContain("var apiVersionContainer = { apiVersion: input.apiVersion ? input.apiVersion : '2.0' };");
script.ShouldContain("'api/v' + apiVersionContainer.apiVersion + '/book'");
script.ShouldNotContain("input.apiVersion =");
script.ShouldNotContain("input = ");
}
[Fact]
public void Should_Default_Query_String_Version_Without_Other_Parameters()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book/count",
("api-version", "api-version", ParameterBindingSources.Query)));
script.ShouldContain("function(api_version, ajaxParams)");
script.ShouldContain("api_version = api_version ? api_version : '2.0';");
script.ShouldContain("'api/app/book/count' + abp.utils.buildQueryString([{ name: 'api-version', value: api_version }])");
}
[Fact]
public void Should_Default_Query_String_Version_Of_Body_Parameter()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book", "POST", new List<string> { "2.0" },
("input", "input", ParameterBindingSources.Body),
("api-version", "api-version", ParameterBindingSources.Query)));
script.ShouldContain("function(input, api_version, ajaxParams)");
script.ShouldContain("api_version = api_version ? api_version : '2.0';");
script.ShouldContain("data: JSON.stringify(input)");
}
[Fact]
public void Should_Default_To_Version_1_When_There_Are_No_Supported_Versions()
{
var script = _generator.CreateScript(BuildAppModel("api/v{apiVersion}/book", "GET", new List<string>(),
("Filter", "input", ParameterBindingSources.Query),
("apiVersion", "input", ParameterBindingSources.Path)));
script.ShouldContain("var apiVersionContainer = { apiVersion: input.apiVersion ? input.apiVersion : '1.0' };");
}
[Fact]
public void Should_Keep_The_Form_Data_Of_A_Versioned_Upload()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book/upload", "POST", new List<string> { "2.0" },
("Name", "input", ParameterBindingSources.Form),
("File", "input", ParameterBindingSources.FormFile),
("api-version", "input", ParameterBindingSources.Query)));
script.ShouldContain("function(input, ajaxParams)");
script.ShouldContain("var apiVersionContainer = { api_version: input.api_version ? input.api_version : '2.0' };");
script.ShouldContain("'api/app/book/upload' + abp.utils.buildQueryString([{ name: 'api-version', value: apiVersionContainer.api_version }])");
script.ShouldContain("data: input,");
script.ShouldNotContain("input = ");
}
[Fact]
public void Should_Not_Overwrite_A_Method_Parameter_Named_Like_The_Version()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book",
("api_version", "api_version", ParameterBindingSources.ModelBinding),
("Filter", "input", ParameterBindingSources.ModelBinding),
("api-version", "input", ParameterBindingSources.Query)));
script.ShouldContain("function(api_version, input, ajaxParams)");
script.ShouldContain("var apiVersionContainer = { api_version: input.api_version ? input.api_version : '2.0' };");
script.ShouldContain("{ name: 'api_version', value: api_version }");
script.ShouldContain("{ name: 'api-version', value: apiVersionContainer.api_version }");
script.ShouldNotContain("var api_version");
}
[Fact]
public void Should_Not_Overwrite_A_Method_Parameter_Named_Like_The_Version_Container()
{
var script = _generator.CreateScript(BuildAppModel("api/app/book",
("apiVersionContainer", "apiVersionContainer", ParameterBindingSources.ModelBinding),
("Filter", "input", ParameterBindingSources.ModelBinding),
("api-version", "input", ParameterBindingSources.Query)));
script.ShouldContain("function(apiVersionContainer, input, ajaxParams)");
script.ShouldContain("var apiVersionContainer_ = { api_version: input.api_version ? input.api_version : '2.0' };");
script.ShouldContain("{ name: 'apiVersionContainer', value: apiVersionContainer }");
script.ShouldContain("{ name: 'api-version', value: apiVersionContainer_.api_version }");
}
private static ApplicationApiDescriptionModel BuildAppModel(string url,
params (string Name, string NameOnMethod, string BindingSourceId)[] parameters)
{
return BuildAppModel(url, "GET", new List<string> { "1.0", "2.0" }, parameters);
}
private static ApplicationApiDescriptionModel BuildAppModel(string url, string httpMethod, List<string> supportedVersions,
params (string Name, string NameOnMethod, string BindingSourceId)[] parameters)
{
var model = ApplicationApiDescriptionModel.Create();
var module = model.GetOrAddModule("app", "Default");
var controller = module.GetOrAddController(
name: "Book",
groupName: null,
isRemoteService: true,
isIntegrationService: false,
apiVersion: null,
type: typeof(object));
var parameterModels = new List<ParameterApiDescriptionModel>();
foreach (var (name, nameOnMethod, bindingSourceId) in parameters)
{
parameterModels.Add(new ParameterApiDescriptionModel
{
Name = name,
NameOnMethod = nameOnMethod,
Type = "System.String",
TypeSimple = "string",
BindingSourceId = bindingSourceId,
DescriptorName = name == nameOnMethod || name is "api-version" or "apiVersion" ? string.Empty : nameOnMethod
});
}
var action = new ActionApiDescriptionModel
{
UniqueName = "GetAsync",
Name = "GetAsync",
HttpMethod = httpMethod,
Url = url,
SupportedVersions = supportedVersions,
ParametersOnMethod = new List<MethodParameterApiDescriptionModel>(),
Parameters = parameterModels,
ReturnValue = new ReturnValueApiDescriptionModel
{
Type = "System.String",
TypeSimple = "string",
},
AuthorizeDatas = new List<AuthorizeDataApiDescriptionModel>(),
};
controller.AddAction("GetAsync", action);
return model;
}
}

423
npm/ng-packs/packages/schematics/src/tests/api-version-parameter.spec.ts

@ -0,0 +1,423 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import { template as lodashTemplate } from 'lodash';
import * as ts from 'typescript';
import { beforeAll, describe, expect, test } from 'vitest';
import { eBindingSourceId } from '../enums';
import { Action, ParameterInBody } from '../models';
import {
createActionToBodyMapper,
createActionToMethodMapper,
createActionToSignatureMapper,
serializeParameters,
} from '../utils/service';
const TEMPLATE_PATH = join(
__dirname,
'..',
'commands',
'api',
'files-service',
'proxy',
'__namespace@dir__',
'__name@kebab__.service.ts.template',
);
function parameter(overrides: Partial<ParameterInBody>): ParameterInBody {
return {
nameOnMethod: overrides.name!,
jsonName: null,
type: 'System.String',
typeSimple: 'string',
isOptional: false,
defaultValue: null,
constraintTypes: null,
bindingSourceId: eBindingSourceId.Query,
descriptorName: '',
...overrides,
} as ParameterInBody;
}
function inputDtoParameter(name: string, bindingSourceId = eBindingSourceId.Model) {
return parameter({ name, nameOnMethod: 'input', bindingSourceId, descriptorName: 'input' });
}
function methodParameter(name: string, typeSimple: string) {
return {
name,
typeAsString: typeSimple,
type: typeSimple,
typeSimple,
isOptional: false,
defaultValue: null,
};
}
const inputOnMethod = methodParameter('input', 'GetBookListInput');
const idOnMethod = methodParameter('id', 'string');
function buildAction(overrides: Partial<Action>): Action {
return {
uniqueName: 'GetListAsync',
name: 'GetListAsync',
httpMethod: 'GET',
url: 'api/app/book',
supportedVersions: ['2.0'],
parametersOnMethod: [],
parameters: [],
returnValue: { type: 'System.String', typeSimple: 'string' },
...overrides,
} as Action;
}
const queryVersionWithInputDto = buildAction({
parametersOnMethod: [inputOnMethod],
parameters: [
inputDtoParameter('Filter'),
inputDtoParameter('MaxResultCount'),
parameter({ name: 'api-version', nameOnMethod: 'input' }),
],
});
const queryVersionWithSimpleParameters = buildAction({
uniqueName: 'GetAsync',
url: 'api/app/book/{id}',
parametersOnMethod: [idOnMethod],
parameters: [
parameter({ name: 'id', bindingSourceId: eBindingSourceId.Path }),
parameter({ name: 'api-version' }),
],
});
const queryVersionWithBody = buildAction({
uniqueName: 'CreateAsync',
httpMethod: 'POST',
parametersOnMethod: [methodParameter('input', 'CreateBookDto')],
parameters: [
parameter({
name: 'input',
type: 'CreateBookDto',
typeSimple: 'CreateBookDto',
bindingSourceId: eBindingSourceId.Body,
}),
parameter({ name: 'api-version' }),
],
});
const queryVersionWithoutParameters = buildAction({
uniqueName: 'GetCountAsync',
url: 'api/app/book/count',
parameters: [parameter({ name: 'api-version' })],
});
const urlSegmentVersionWithInputDto = buildAction({
uniqueName: 'GetPagedAsync',
url: 'api/v{apiVersion}/book',
parametersOnMethod: [inputOnMethod],
parameters: [
inputDtoParameter('Filter', eBindingSourceId.Query),
parameter({
name: 'apiVersion',
nameOnMethod: 'input',
bindingSourceId: eBindingSourceId.Path,
}),
],
});
const urlSegmentVersionWithSimpleParameters = buildAction({
uniqueName: 'GetByIdAsync',
url: 'api/v{apiVersion}/book/{id}',
parametersOnMethod: [idOnMethod],
parameters: [
parameter({ name: 'id', bindingSourceId: eBindingSourceId.Path }),
parameter({ name: 'apiVersion', bindingSourceId: eBindingSourceId.Path }),
],
});
const versionWithoutSupportedVersions = buildAction({
uniqueName: 'GetLegacyAsync',
url: 'api/app/book/legacy',
supportedVersions: [],
parameters: [parameter({ name: 'api-version' })],
});
describe('api version parameter mapping', () => {
const mapSignature = createActionToSignatureMapper();
const mapBody = createActionToBodyMapper();
test('query string version with an input DTO is bound to the apiVersion argument', () => {
expect(serializeParameters(mapSignature(queryVersionWithInputDto).parameters)).toBe(
'input: GetBookListInput, apiVersion: string = "2.0", config?: Partial<Rest.Config>',
);
expect(mapBody(queryVersionWithInputDto).params).toEqual([
'filter: input.filter',
'maxResultCount: input.maxResultCount',
'["api-version"]: apiVersion',
]);
});
test('query string version with simple parameters is bound to the apiVersion argument', () => {
expect(serializeParameters(mapSignature(queryVersionWithSimpleParameters).parameters)).toBe(
'id: string, apiVersion: string = "2.0", config?: Partial<Rest.Config>',
);
const body = mapBody(queryVersionWithSimpleParameters);
expect(body.url).toBe('`/api/app/book/${id}`');
expect(body.params).toEqual(['["api-version"]: apiVersion']);
});
test('query string version with a body keeps the body bound to the input', () => {
expect(serializeParameters(mapSignature(queryVersionWithBody).parameters)).toBe(
'input: CreateBookDto, apiVersion: string = "2.0", config?: Partial<Rest.Config>',
);
const body = mapBody(queryVersionWithBody);
expect(body.body).toBe('input');
expect(body.params).toEqual(['["api-version"]: apiVersion']);
});
test('query string version without other parameters is bound to the apiVersion argument', () => {
expect(serializeParameters(mapSignature(queryVersionWithoutParameters).parameters)).toBe(
'apiVersion: string = "2.0", config?: Partial<Rest.Config>',
);
expect(mapBody(queryVersionWithoutParameters).params).toEqual(['["api-version"]: apiVersion']);
});
test('url segment version with an input DTO is bound to the apiVersion argument', () => {
expect(serializeParameters(mapSignature(urlSegmentVersionWithInputDto).parameters)).toBe(
'input: GetBookListInput, apiVersion: string = "2.0", config?: Partial<Rest.Config>',
);
const body = mapBody(urlSegmentVersionWithInputDto);
expect(body.url).toBe('`/api/v${apiVersion}/book`');
expect(body.params).toEqual(['filter: input.filter']);
});
test('uses the latest supported version as the default value', () => {
const action = buildAction({
supportedVersions: ['1.0', '2.0', '3.0'],
parameters: [parameter({ name: 'api-version' })],
});
expect(serializeParameters(mapSignature(action).parameters)).toBe(
'apiVersion: string = "3.0", config?: Partial<Rest.Config>',
);
});
test('falls back to 1.0 when the action has no supported versions', () => {
expect(serializeParameters(mapSignature(versionWithoutSupportedVersions).parameters)).toBe(
'apiVersion: string = "1.0", config?: Partial<Rest.Config>',
);
expect(mapBody(versionWithoutSupportedVersions).params).toEqual([
'["api-version"]: apiVersion',
]);
});
test('leaves actions without a version parameter unchanged', () => {
const action = buildAction({
parametersOnMethod: [inputOnMethod],
parameters: [inputDtoParameter('Filter')],
});
expect(serializeParameters(mapSignature(action).parameters)).toBe(
'input: GetBookListInput, config?: Partial<Rest.Config>',
);
expect(mapBody(action).params).toEqual(['filter: input.filter']);
});
});
interface CapturedRequest {
method: string;
url: string;
params?: Record<string, unknown>;
body?: unknown;
}
const GENERATED_SERVICE_PATH = '/proxy/book.service.ts';
const VIRTUAL_FILES: Record<string, string> = {
'/proxy/models.ts': `
export interface GetBookListInput { filter?: string; maxResultCount?: number; }
export interface CreateBookDto { name: string; }
`,
'/proxy/ambient.d.ts': `
declare module '@abp/ng.core' {
export namespace Rest {
export interface Config { apiName?: string; [key: string]: any; }
}
export class RestService {
request<TBody, TResponse>(req: any, config?: any): import('rxjs').Observable<TResponse>;
}
}
declare module '@angular/core' {
export function Injectable(opts?: any): ClassDecorator;
export function inject<T>(token: { new (...args: any[]): T }): T;
}
declare module 'rxjs' {
export class Observable<T> { subscribe(...args: any[]): unknown; }
}
`,
};
function renderService(actions: Action[]) {
const mapMethod = createActionToMethodMapper();
return lodashTemplate(readFileSync(TEMPLATE_PATH, 'utf8'), {
imports: {
camel: (s: string) => s.charAt(0).toLowerCase() + s.slice(1),
serializeParameters,
},
})({
apiName: 'Default',
name: 'Book',
resourceApi: false,
imports: [
{
keyword: 'import type',
specifiers: ['CreateBookDto', 'GetBookListInput'],
path: './models',
},
{ keyword: 'import', specifiers: ['RestService', 'Rest'], path: '@abp/ng.core' },
{ keyword: 'import', specifiers: ['Injectable', 'inject'], path: '@angular/core' },
],
methods: actions.map(mapMethod),
});
}
function typeCheck(source: string) {
const sources: Record<string, string> = { ...VIRTUAL_FILES, [GENERATED_SERVICE_PATH]: source };
const compilerOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ES2022,
moduleResolution: ts.ModuleResolutionKind.Bundler,
experimentalDecorators: true,
strict: true,
noEmit: true,
skipLibCheck: true,
};
const baseHost = ts.createCompilerHost(compilerOptions, true);
const host: ts.CompilerHost = {
...baseHost,
getSourceFile: (fileName, languageVersion, onError) =>
sources[fileName] != null
? ts.createSourceFile(fileName, sources[fileName], languageVersion, true)
: baseHost.getSourceFile(fileName, languageVersion, onError),
fileExists: fileName => sources[fileName] != null || baseHost.fileExists(fileName),
readFile: fileName => sources[fileName] ?? baseHost.readFile(fileName),
directoryExists: directoryName =>
directoryName === '/proxy' || (baseHost.directoryExists?.(directoryName) ?? false),
};
const program = ts.createProgram(Object.keys(sources), compilerOptions, host);
return ts
.getPreEmitDiagnostics(program)
.filter(d => d.category === ts.DiagnosticCategory.Error)
.map(d => `TS${d.code}: ${ts.flattenDiagnosticMessageText(d.messageText, '\n')}`);
}
// Renders the real service template, type checks it and runs the generated methods against a fake
// RestService, so the test fails on code that does not compile or sends the wrong version.
function createGeneratedService(actions: Action[]) {
const source = renderService(actions);
const errors = typeCheck(source);
const requests: CapturedRequest[] = [];
if (errors.length) {
return { errors, requests, service: undefined };
}
const restService = { request: (request: CapturedRequest) => requests.push(request) };
const modules: Record<string, unknown> = {
'@abp/ng.core': { RestService: class {} },
'@angular/core': { Injectable: () => (target: unknown) => target, inject: () => restService },
};
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.CommonJS,
experimentalDecorators: true,
},
});
const module = { exports: {} as Record<string, new () => Record<string, Function>> };
new Function('module', 'exports', 'require', outputText)(
module,
module.exports,
(name: string) => modules[name],
);
return { errors, requests, service: new module.exports.BookService() };
}
describe('api version parameter in the generated service', () => {
let generated: ReturnType<typeof createGeneratedService>;
let service: Record<string, Function>;
beforeAll(() => {
generated = createGeneratedService([
queryVersionWithInputDto,
queryVersionWithSimpleParameters,
queryVersionWithBody,
queryVersionWithoutParameters,
urlSegmentVersionWithInputDto,
urlSegmentVersionWithSimpleParameters,
versionWithoutSupportedVersions,
]);
service = generated.service!;
});
const input = { filter: 'f', maxResultCount: 5 };
const lastRequest = () => generated.requests[generated.requests.length - 1];
test('type checks', () => {
expect(generated.errors).toEqual([]);
});
test.each([
['getList', [input], '2.0'],
['get', ['1'], '2.0'],
['create', [{ name: 'n' }], '2.0'],
['getCount', [], '2.0'],
['getLegacy', [], '1.0'],
])('%s sends the default query string version', (method, args, version) => {
service[method](...args);
expect(lastRequest().params!['api-version']).toBe(version);
});
test.each([
['getList', [input]],
['get', ['1']],
['create', [{ name: 'n' }]],
['getCount', []],
['getLegacy', []],
])('%s sends the query string version passed by the caller', (method, args) => {
service[method](...args, '3.0');
expect(lastRequest().params!['api-version']).toBe('3.0');
});
test('getList sends the input DTO properties and keeps the input unchanged', () => {
service.getList(input);
expect(lastRequest().params).toEqual({
filter: 'f',
maxResultCount: 5,
'api-version': '2.0',
});
expect(input).toEqual({ filter: 'f', maxResultCount: 5 });
});
test('create sends the input as the body', () => {
const dto = { name: 'n' };
service.create(dto);
expect(lastRequest()).toMatchObject({ method: 'POST', body: dto });
});
test.each([
['getPaged', [input], '/api/v2.0/book'],
['getById', ['1'], '/api/v2.0/book/1'],
])('%s puts the default version into the url', (method, args, url) => {
service[method](...args);
expect(lastRequest().url).toBe(url);
});
test.each([
['getPaged', [input], '/api/v3.0/book'],
['getById', ['1'], '/api/v3.0/book/1'],
])('%s puts the version passed by the caller into the url', (method, args, url) => {
service[method](...args, '3.0');
expect(lastRequest().url).toBe(url);
});
});

33
npm/ng-packs/packages/schematics/src/utils/service.ts

@ -4,6 +4,7 @@ import {
Controller,
Import,
Method,
ParameterInBody,
Property,
Service,
ServiceGeneratorParams,
@ -98,7 +99,9 @@ export function createActionToMethodMapper() {
export function createActionToBodyMapper() {
const adaptType = createTypeAdapter();
return ({ httpMethod, parameters, returnValue, url }: Action) => {
return (action: Action) => {
const { httpMethod, returnValue, url } = action;
const parameters = bindVersionParameterToSignature(action);
let responseType = adaptType(returnValue.typeSimple);
if (responseType.includes('enum')) {
const type = returnValue.typeSimple.replace('enum', returnValue.type);
@ -323,22 +326,38 @@ function getMethodNameFromAction(action: Action): string {
return action.uniqueName.split('Async')[0];
}
function getVersionParameter(action: Action) {
const versionParameter = action.parameters.find(
p =>
(p.name == 'apiVersion' && p.bindingSourceId == eBindingSourceId.Path) ||
(p.name == 'api-version' && p.bindingSourceId == eBindingSourceId.Query),
function isVersionParameter(parameter: ParameterInBody) {
return (
(parameter.name == 'apiVersion' && parameter.bindingSourceId == eBindingSourceId.Path) ||
(parameter.name == 'api-version' && parameter.bindingSourceId == eBindingSourceId.Query)
);
}
function getVersionParameter(action: Action) {
const versionParameter = action.parameters.find(isVersionParameter);
const bestVersion = findBestApiVersion(action);
return versionParameter && bestVersion
? {
...versionParameter,
name: camelizeHyphen(versionParameter.name),
defaultValue: `"${bestVersion}"`,
defaultValue: bestVersion,
}
: null;
}
// The API definition reports the input DTO as `nameOnMethod` of the version parameter when the
// action takes a DTO, so the value has to come from the `apiVersion` argument of the signature.
function bindVersionParameterToSignature(action: Action) {
const versionParameter = getVersionParameter(action);
if (!versionParameter) {
return action.parameters;
}
return action.parameters.map(p =>
isVersionParameter(p) ? { ...p, nameOnMethod: versionParameter.name } : p,
);
}
// Implementation of https://github.com/abpframework/abp/commit/c3f77c1229508279015054a9b4f5586404a88a14#diff-a4dbf6be9a1aa21d8294f11047774949363ee6b601980bf3225e8046c0748c9eR101
function findBestApiVersion(action: Action) {
/*

Loading…
Cancel
Save