static void WriteCs(IndentedTextWriter writer, List <ValidMethod> valids) { writer.WriteLine("using System.Net;"); writer.WriteLine("using System.Threading.Tasks;"); writer.WriteLine(); writer.WriteLine("namespace Caefte"); writer.WriteBlock(() => { writer.WriteLine("public sealed partial class Controller"); writer.WriteBlock(() => { writer.WriteLine("public async Task<bool> Handle(HttpListenerRequest request, HttpListenerResponse response)"); writer.WriteBlock(() => { writer.WriteLine("switch (request.Url.AbsolutePath)"); writer.WriteBlock(() => { WriteSwitch(writer, valids); writer.WriteLine("default:"); writer.Indent++; writer.WriteLine("await Task.Yield();"); writer.WriteLine("return false;"); writer.Indent--; }); }); }); }); }
public bool Render(CSharpModuleContext context, Fragment fragment, IndentedTextWriter writer) { if (!(fragment is ServiceFragment classFragment)) { return(false); } if (classFragment.Hints.TryGetValue("source-type", out var sourceType)) { writer.WriteIndentedLine($"// source: {sourceType}"); writer.WriteSeparatingLine(); } context.Import("Odachi.Abstractions"); using (writer.WriteIndentedBlock(prefix: $"public class {classFragment.Name} ")) { using (writer.WriteIndentedBlock(prefix: $"public {classFragment.Name}(IRpcClient client) ")) { writer.WriteIndentedLine("this._client = client;"); } writer.WriteIndentedLine("private IRpcClient _client;"); writer.WriteSeparatingLine(); foreach (var method in classFragment.Methods) { context.Import("System.Threading.Tasks"); var rpcModuleName = method.Hints["jsonrpc-module-name"]; var rpcMethodName = method.Hints["jsonrpc-method-name"] ?? method.Name; writer.WriteIndent(); if (method.ReturnType.Name == "void") { writer.Write($"public Task "); } else { writer.Write($"public Task<{context.Resolve(method.ReturnType)}> "); } writer.Write($"{CS.Method(method.Name)}Async({string.Join(", ", method.Parameters.Select(p => $"{context.Resolve(p.Type)} {p.Name}"))})"); using (writer.WriteBlock()) { if (method.ReturnType.Name == "void") { writer.WriteIndentedLine($"return _client.CallAsync(\"{rpcModuleName}\", \"{rpcMethodName}\", new {{ {string.Join(", ", method.Parameters.Select(p => p.Name))} }});"); } else { writer.WriteIndentedLine($"return _client.CallAsync<{context.Resolve(method.ReturnType)}>(\"{rpcModuleName}\", \"{rpcMethodName}\", new {{ {string.Join(", ", method.Parameters.Select(p => p.Name))} }});"); } } writer.WriteLine(); writer.WriteSeparatingLine(); } } return(true); }
static void WriteSwitch(IndentedTextWriter writer, List <ValidMethod> valids) { foreach (var valid in valids) { writer.WriteLine($"case \"{valid.Path}\":"); writer.WriteBlock(() => { if (valid.IsAsync) { writer.WriteLine($"var result = await new {valid.Type.Name}().{valid.MethodInfo.Name}();"); } else { writer.WriteLine($"var result = new {valid.Type.Name}().{valid.MethodInfo.Name}();"); } writer.WriteLine("Write(response, result);"); writer.WriteLine("return true;"); }); } }