Skip to content

Commit

Permalink
simplify api generator
Browse files Browse the repository at this point in the history
  • Loading branch information
fakefeik committed Jan 11, 2024
1 parent e9cee58 commit 9ba8da4
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 79 deletions.
8 changes: 4 additions & 4 deletions AspNetCoreExample.Generator/output/api/NotesApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
// TypeScriptContractGenerator's generated content
import { Guid } from './../DataTypes/Guid';
import { BlogEntry } from './../DataTypes/BlogEntry';
import { ApiBase } from './../ApiBase/ApiBase';
import { request } from './../ApiBase/ApiBase';
import { url } from './../ApiBase/ApiBase';

export class NotesApi extends ApiBase implements INotesApi {
export class NotesApi implements INotesApi {
addEntry(userId: Guid, entry: BlogEntry): Promise<void> {
return this.makePostRequest(url`/v1/user/${userId}/blog`, entry);
return request('POST', url`/v1/user/${userId}/blog`, entry);
}

addEntries(userId: Guid, entries: BlogEntry[]): Promise<void> {
return this.makePostRequest(url`/v1/user/${userId}/blog/batch`, entries);
return request('POST', url`/v1/user/${userId}/blog/batch`, entries);
}

};
Expand Down
12 changes: 6 additions & 6 deletions AspNetCoreExample.Generator/output/api/UserApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@
// TypeScriptContractGenerator's generated content
import { User } from './../DataTypes/User';
import { Guid } from './../DataTypes/Guid';
import { ApiBase } from './../ApiBase/ApiBase';
import { request } from './../ApiBase/ApiBase';
import { url } from './../ApiBase/ApiBase';

export class UserApi extends ApiBase implements IUserApi {
export class UserApi implements IUserApi {
createUser(user: User): Promise<void> {
return this.makePostRequest(url`/v1/users`, user);
return request('POST', url`/v1/users`, user);
}

deleteUser(userId: Guid): Promise<void> {
return this.makeDeleteRequest(url`/v1/users/${userId}`);
return request('DELETE', url`/v1/users/${userId}`);
}

getUser(userId: Guid): Promise<User> {
return this.makeGetRequest(url`/v1/users/${userId}`);
return request('GET', url`/v1/users/${userId}`);
}

searchUsers(name: string): Promise<User[]> {
return this.makeGetRequest(url`/v1/users?name=${name}`);
return request('GET', url`/v1/users?name=${name}`);
}

};
Expand Down
12 changes: 6 additions & 6 deletions AspNetCoreExample.Generator/output/api/WeatherForecastApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@
// TypeScriptContractGenerator's generated content
import { WeatherForecast } from './../DataTypes/WeatherForecast';
import { Guid } from './../DataTypes/Guid';
import { ApiBase } from './../ApiBase/ApiBase';
import { request } from './../ApiBase/ApiBase';
import { url } from './../ApiBase/ApiBase';

export class WeatherForecastApi extends ApiBase implements IWeatherForecastApi {
export class WeatherForecastApi implements IWeatherForecastApi {
get(): Promise<WeatherForecast[]> {
return this.makeGetRequest(url`/WeatherForecast`);
return request('GET', url`/WeatherForecast`);
}

update(city: string, forecast: WeatherForecast): Promise<void> {
return this.makePostRequest(url`/WeatherForecast/Update/${city}`, forecast);
return request('POST', url`/WeatherForecast/Update/${city}`, forecast);
}

reset(seed: number): Promise<void> {
return this.makePostRequest(url`/Reset?seed=${seed}`);
return request('POST', url`/Reset?seed=${seed}`);
}

urlForDownload(city: string): string {
Expand All @@ -27,7 +27,7 @@ export class WeatherForecastApi extends ApiBase implements IWeatherForecastApi {
}

newGuid(): Promise<Guid> {
return this.makeGetRequest(url`/WeatherForecast/none`);
return request('GET', url`/WeatherForecast/none`);
}

};
Expand Down
48 changes: 9 additions & 39 deletions AspNetCoreExample.Generator/output/apiBase/ApiBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,14 @@

export const url = String.raw;

export class ApiBase {
public async makeGetRequest(url: string, body?: any): Promise<any> {
const response = await fetch(url, {
method: "GET",
});
return await response.json();
}

public async makePostRequest(url: string, body?: any): Promise<any> {
const response = await fetch(url, {
method: "POST",
body: body && JSON.stringify(body),
});
const textResult = await response.text();
if (textResult !== "") {
return JSON.parse(textResult);
}
}

public async makePutRequest(url: string, body?: any): Promise<any> {
const response = await fetch(url, {
method: "PUT",
body: body && JSON.stringify(body),
});
const textResult = await response.text();
if (textResult !== "") {
return JSON.parse(textResult);
}
}
export const request = async (method: string, url: string, body?: any): Promise<any> => {
const response = await fetch(url, {
method: method,
body: body && JSON.stringify(body),
});

public async makeDeleteRequest(url: string, body?: any): Promise<any> {
const response = await fetch(url, {
method: "DELETE",
body: body && JSON.stringify(body),
});
const textResult = await response.text();
if (textResult !== "") {
return JSON.parse(textResult);
}
const textResult = await response.text();
if (textResult !== "") {
return JSON.parse(textResult);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace SkbKontur.TypeScript.ContractGenerator.TypeBuilders.ApiController
{
public class ApiBaseLocation
{
public string RequestMethodName { get; set; }
public string UrlTagName { get; set; }
public string Location { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@ public override void Initialize(ITypeGenerator typeGenerator)
BuildAndImportType = t => typeGenerator.BuildAndImportType(Unit, t);

var baseApi = ApiCustomization.GetApiBase(Type);
var urlTag = ApiCustomization.GetUrlTag(Type);

Unit.AddSymbolImport(baseApi.Name, baseApi.Location);
Unit.AddSymbolImport(urlTag.Name, urlTag.Location);
Unit.AddSymbolImport(baseApi.RequestMethodName, baseApi.Location);
Unit.AddSymbolImport(baseApi.UrlTagName, baseApi.Location);

var apiName = ApiCustomization.GetApiClassName(Type);
var interfaceName = ApiCustomization.GetApiInterfaceName(Type);
Expand All @@ -37,7 +35,6 @@ public override void Initialize(ITypeGenerator typeGenerator)

var apiClassDefinition = new TypeScriptClassDefinition
{
BaseClass = new TypeScriptTypeReference(baseApi.Name),
ImplementedInterfaces = new TypeScriptType[] {new TypeScriptTypeReference(interfaceName)},
};

Expand Down Expand Up @@ -102,13 +99,17 @@ protected virtual TypeScriptReturnStatement CreateCall(IMethodInfo methodInfo)
return new TypeScriptReturnStatement(routeExpression);
}

var requestMethodName = ApiCustomization.GetApiBase(methodInfo.DeclaringType!).RequestMethodName;
var verb = ApiCustomization.GetMethodVerb(methodInfo);
var requestExpression = new TypeScriptVariableReference(requestMethodName);
var methodExpression = (TypeScriptExpression)new TypeScriptStringLiteral(verb);
var bodyExpression = ApiCustomization.GetMethodBodyExpression(methodInfo);
var arguments = bodyExpression == null
? new[] {routeExpression}
: new[] {routeExpression, bodyExpression};
? new[] {methodExpression, routeExpression}
: new[] {methodExpression, routeExpression, bodyExpression};

return new TypeScriptReturnStatement(
new TypeScriptMethodCallExpression(new TypeScriptThisReference(), ApiCustomization.GetMethodVerb(methodInfo), arguments)
new TypeScriptFunctionCallExpression(requestExpression, arguments)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,10 @@ namespace SkbKontur.TypeScript.ContractGenerator.TypeBuilders.ApiController
{
public class DefaultApiCustomization : IApiCustomization
{
public virtual TypeLocation GetApiBase(ITypeInfo type) => new TypeLocation
public virtual ApiBaseLocation GetApiBase(ITypeInfo type) => new ApiBaseLocation
{
Name = "ApiBase",
Location = "ApiBase/ApiBase",
};

public virtual TypeLocation GetUrlTag(ITypeInfo type) => new TypeLocation
{
Name = "url",
RequestMethodName = "request",
UrlTagName = "url",
Location = "ApiBase/ApiBase",
};

Expand All @@ -47,7 +42,7 @@ public virtual IParameterInfo[] GetMethodParameters(IMethodInfo methodInfo) =>

public virtual bool IsUrlMethod(IMethodInfo methodInfo)
{
return GetMethodVerb(methodInfo) == "makeGetRequest" && ResolveReturnType(methodInfo.ReturnType).Equals(TypeInfo.From(typeof(void)));
return GetMethodVerb(methodInfo) == "GET" && ResolveReturnType(methodInfo.ReturnType).Equals(TypeInfo.From(typeof(void)));
}

public virtual bool IsAsyncMethod(IMethodInfo methodInfo) => false;
Expand All @@ -57,19 +52,25 @@ public virtual string GetMethodVerb(IMethodInfo methodInfo)
var attributes = methodInfo.GetAttributes(inherit : false);

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpGet)))
return "makeGetRequest";
return "GET";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpPost)))
return "makePostRequest";
return "POST";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpPut)))
return "makePutRequest";
return "PUT";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpDelete)))
return "makeDeleteRequest";
return "DELETE";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpPatch)))
return "makePatchRequest";
return "PATCH";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpHead)))
return "HEAD";

if (attributes.Any(x => x.HasName(KnownTypeNames.Attributes.HttpOptions)))
return "OPTIONS";

throw new NotSupportedException($"Unresolved http verb for method {methodInfo.Name} at controller {methodInfo.DeclaringType?.Name}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ namespace SkbKontur.TypeScript.ContractGenerator.TypeBuilders.ApiController
{
public interface IApiCustomization
{
public TypeLocation GetApiBase(ITypeInfo type);
public TypeLocation GetUrlTag(ITypeInfo type);
public ApiBaseLocation GetApiBase(ITypeInfo type);

string GetApiClassName(ITypeInfo type);
string GetApiInterfaceName(ITypeInfo type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public static class Attributes
public const string HttpPut = "HttpPut";
public const string HttpPatch = "HttpPatch";
public const string HttpDelete = "HttpDelete";
public const string HttpHead = "HttpHead";
public const string HttpOptions = "HttpOptions";
public const string FromBody = "FromBody";
}
}
Expand Down

0 comments on commit 9ba8da4

Please sign in to comment.