Compare commits
15 Commits
46aff0c61b
...
main
Author | SHA1 | Date | |
---|---|---|---|
036897ecab | |||
bc19a315da | |||
4465c62163 | |||
fea830b295 | |||
7bc9adebaa | |||
e15ce1f0a0 | |||
f93755604a | |||
f401d58f07 | |||
132390fa35 | |||
04f82b655b | |||
5106424a32 | |||
137a3659b7 | |||
b3b202c9f9 | |||
6e947bde57 | |||
a291851b5a |
42
JsonRPC.sln
Normal file
42
JsonRPC.sln
Normal file
@ -0,0 +1,42 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.002.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{ECEBC2A1-9382-44B5-94A6-305DC8235859}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp", "templates\CSharp\CSharp.csproj", "{16231421-DB23-46D0-AFA8-81099E3CF97A}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B6AB75C7-58FC-4F62-AFAA-ED8FEEBF2E1C}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CSharp", "CSharp", "{833192BE-67E8-425F-9AA7-23532485682A}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp_Example", "examples\CSharp\Example\CSharp_Example.csproj", "{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{16231421-DB23-46D0-AFA8-81099E3CF97A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{16231421-DB23-46D0-AFA8-81099E3CF97A} = {ECEBC2A1-9382-44B5-94A6-305DC8235859}
|
||||
{833192BE-67E8-425F-9AA7-23532485682A} = {B6AB75C7-58FC-4F62-AFAA-ED8FEEBF2E1C}
|
||||
{3BD8D8BF-46ED-4F52-BD78-8B22FF3A77A2} = {833192BE-67E8-425F-9AA7-23532485682A}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {ED59162F-B7E7-4EA2-91D4-7F6D1BFBB820}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
11
README.md
11
README.md
@ -6,6 +6,9 @@ Type/Service definition language and code generator for json-rpc 2.0. Currently
|
||||
| ------- | --------------------------------- |
|
||||
| ts-node | Typescript for NodeJS |
|
||||
| ts-esm | Typescript in ESM format for Deno |
|
||||
| rust | Rust |
|
||||
| dart | Dart |
|
||||
| c# | C# |
|
||||
|
||||
## Usage
|
||||
|
||||
@ -23,7 +26,7 @@ enum TestEnum {
|
||||
type Test {
|
||||
testen: TestEnum;
|
||||
someString: string;
|
||||
someNumber: number;
|
||||
someNumber?: number;
|
||||
array: string[];
|
||||
map: {number, TestEnum};
|
||||
}
|
||||
@ -44,4 +47,8 @@ Then run the generator like this `jrpc compile test.jrpc -o=ts-node:output/`.
|
||||
|
||||
This will generate the Client and Server code in the specified folder.
|
||||
|
||||
//TODO: Make Documentation better
|
||||
## TODOS
|
||||
|
||||
1. Documentation
|
||||
2. Null Checks/Enforcements in all languages
|
||||
3. More and better tests
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
@ -41,6 +41,10 @@ class TestSrvimpl : Example.TestServiceServer<int>
|
||||
throw new Exception("This is a remote error :)");
|
||||
}
|
||||
|
||||
public override Task<double> FunctionWithKeywords(double type, double static_, double event_, int ctx)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
class CopyTransportS2 : Example.JRpcTransport
|
||||
|
@ -52,6 +52,8 @@ service TestService {
|
||||
|
||||
|
||||
FunctionWithArrayAsParamAndReturn(values1: float[], values2: float[]): float[];
|
||||
|
||||
FunctionWithKeywords(type: float, static: float, event: float): float;
|
||||
}
|
||||
|
||||
type Test2 {
|
||||
@ -59,6 +61,12 @@ type Test2 {
|
||||
age: int;
|
||||
}
|
||||
|
||||
type TestKeywords {
|
||||
type: float;
|
||||
static: float;
|
||||
event: float;
|
||||
}
|
||||
|
||||
service SimpleTestService {
|
||||
@Description("asdasdasd")
|
||||
GetTest(name: string, age: int): Test2;
|
||||
|
@ -1,5 +1,5 @@
|
||||
type TestAtom {
|
||||
val_number: float;
|
||||
val_boolean: boolean;
|
||||
val_string: string;
|
||||
val_number?: float;
|
||||
val_boolean?: boolean;
|
||||
val_string?: string;
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hibas123/jrpcgen",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.20",
|
||||
"main": "lib/index.js",
|
||||
"license": "MIT",
|
||||
"packageManager": "yarn@3.1.1",
|
||||
|
@ -4,13 +4,15 @@ import yargs from "yargs";
|
||||
import { hideBin } from "yargs/helpers";
|
||||
import startCompile, { Target, Targets } from "./process";
|
||||
|
||||
const pkg = require("../package.json");
|
||||
|
||||
import dbg from "debug";
|
||||
const log = dbg("app");
|
||||
|
||||
dbg.disable();
|
||||
|
||||
yargs(hideBin(process.argv))
|
||||
.version("1.0.0")
|
||||
.version(pkg.version)
|
||||
.command(
|
||||
"compile <input>",
|
||||
"Compile source",
|
||||
|
@ -14,6 +14,7 @@ export interface TypeFieldDefinition {
|
||||
name: string;
|
||||
type: string;
|
||||
array: boolean;
|
||||
optional: boolean;
|
||||
map?: string;
|
||||
}
|
||||
|
||||
@ -127,6 +128,7 @@ export default function get_ir(parsed: Parsed): IR {
|
||||
type: field.fieldtype,
|
||||
array: field.array,
|
||||
map: field.map,
|
||||
optional: field.optional,
|
||||
};
|
||||
});
|
||||
steps.push([
|
||||
|
@ -16,6 +16,7 @@ export interface ImportStatement extends DefinitionNode {
|
||||
export interface TypeFieldStatement extends DefinitionNode {
|
||||
type: "type_field";
|
||||
name: string;
|
||||
optional: boolean;
|
||||
fieldtype: string;
|
||||
array: boolean;
|
||||
map?: string;
|
||||
@ -114,8 +115,8 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
||||
return idx;
|
||||
};
|
||||
|
||||
const eatText = (): [string, number] => {
|
||||
checkTypes("text");
|
||||
const eatText = (allowKeyword?: boolean): [string, number] => {
|
||||
checkTypes(...(allowKeyword ? ["text", "keyword"] : ["text"]));
|
||||
let val = currentToken.value;
|
||||
let idx = currentToken.startIdx;
|
||||
eatToken();
|
||||
@ -139,8 +140,7 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
||||
const checkTypes = (...types: string[]) => {
|
||||
if (types.indexOf(currentToken.type) < 0) {
|
||||
throw new ParserError(
|
||||
`Unexpected token value, expected ${types.join(" | ")}, received '${
|
||||
currentToken.value
|
||||
`Unexpected token value, expected ${types.join(" | ")}, received '${currentToken.value
|
||||
}'`,
|
||||
currentToken
|
||||
);
|
||||
@ -170,6 +170,11 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
||||
const idx = currentToken.startIdx;
|
||||
let name = currentToken.value;
|
||||
eatToken();
|
||||
let optional = false;
|
||||
if (currentToken.type === "questionmark") {
|
||||
eatToken("?");
|
||||
optional = true;
|
||||
}
|
||||
eatToken(":");
|
||||
|
||||
let array = false;
|
||||
@ -198,6 +203,7 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
||||
array,
|
||||
map: mapKey,
|
||||
location: { file, idx },
|
||||
optional
|
||||
};
|
||||
};
|
||||
|
||||
@ -345,7 +351,7 @@ export default function parse(tokens: Token[], file: string): Parsed {
|
||||
|
||||
if (currentToken.value !== ")") {
|
||||
while (true) {
|
||||
const [name] = eatText();
|
||||
const [name] = eatText(true);
|
||||
eatToken(":");
|
||||
const [type] = eatText();
|
||||
let array = false;
|
||||
|
@ -46,15 +46,22 @@ function indexToLineAndCol(src: string, index: number) {
|
||||
return { line, col };
|
||||
}
|
||||
|
||||
function resolve(base: string, ...parts: string[]) {
|
||||
if (base.startsWith("http://") || base.startsWith("https://")) {
|
||||
function resolve(base: string, sub?: string) {
|
||||
if (sub && (sub.startsWith("http://") || sub.startsWith("https://"))) {
|
||||
let u = new URL(sub);
|
||||
return u.href;
|
||||
} else if (base.startsWith("http://") || base.startsWith("https://")) {
|
||||
let u = new URL(base);
|
||||
for (const part of parts) {
|
||||
u = new URL(part, u);
|
||||
if (sub) {
|
||||
if (!sub.endsWith(".jrpc")) {
|
||||
sub += ".jrpc";
|
||||
}
|
||||
u = new URL(sub, u);
|
||||
}
|
||||
return u.href;
|
||||
} else {
|
||||
return Path.resolve(base, ...parts);
|
||||
if (!sub) return Path.resolve(base);
|
||||
else return Path.resolve(Path.dirname(base), sub + ".jrpc");
|
||||
}
|
||||
}
|
||||
|
||||
@ -151,13 +158,7 @@ async function processFile(
|
||||
let resolved: Parsed = [];
|
||||
for (const statement of parsed) {
|
||||
if (statement.type == "import") {
|
||||
let res: string;
|
||||
if (file.startsWith("http://") || file.startsWith("https://")) {
|
||||
res = resolve(file, statement.path + ".jrpc");
|
||||
} else {
|
||||
const base = Path.dirname(file);
|
||||
res = resolve(base, statement.path + ".jrpc");
|
||||
}
|
||||
let res = resolve(file, statement.path);
|
||||
resolved.push(...((await processFile(ctx, res)) || []));
|
||||
} else {
|
||||
resolved.push(statement);
|
||||
|
@ -8,6 +8,7 @@ import {
|
||||
|
||||
import { CompileTarget } from "../compile";
|
||||
import { LineAppender } from "../utils";
|
||||
import chalk from "chalk";
|
||||
|
||||
const conversion = {
|
||||
boolean: "bool",
|
||||
@ -22,6 +23,16 @@ function toCSharpType(type: string): string {
|
||||
return (conversion as any)[type] || type;
|
||||
}
|
||||
|
||||
// TODO: Add other keywords as well!
|
||||
const keywords = new Set(["event", "internal", "public", "private", "static"]);
|
||||
|
||||
const fixKeywordName = (name: string) => {
|
||||
if (keywords.has(name)) {
|
||||
return `${name}_`;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
name: string = "c#";
|
||||
|
||||
@ -61,11 +72,20 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
a(0, ``);
|
||||
a(0, `public class ${definition.name} {`);
|
||||
for (const field of definition.fields) {
|
||||
let fn = field.name;
|
||||
if (keywords.has(field.name)) {
|
||||
console.log(
|
||||
chalk.yellow("[RUST] WARNING:"),
|
||||
`Field name '${fn}' is not allowed in C#. Renaming to '${fn}_'`
|
||||
);
|
||||
fn = fixKeywordName(fn);
|
||||
a(1, `[JsonPropertyName("${fn}")]`);
|
||||
}
|
||||
|
||||
if (field.array) {
|
||||
a(
|
||||
1,
|
||||
`public IList<${toCSharpType(field.type)}>? ${
|
||||
field.name
|
||||
`public IList<${toCSharpType(field.type)}>? ${fn
|
||||
} { get; set; }`
|
||||
);
|
||||
} else if (field.map) {
|
||||
@ -73,12 +93,12 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
1,
|
||||
`public Dictionary<${toCSharpType(field.map)}, ${toCSharpType(
|
||||
field.type
|
||||
)}>? ${field.name} { get; set; }`
|
||||
)}>? ${fn} { get; set; }`
|
||||
);
|
||||
} else {
|
||||
a(
|
||||
1,
|
||||
`public ${toCSharpType(field.type)}? ${field.name} { get; set; }`
|
||||
`public ${toCSharpType(field.type)}? ${fn} { get; set; }`
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -127,10 +147,12 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
for (const fnc of definition.functions) {
|
||||
let params = fnc.inputs
|
||||
.map((inp) => {
|
||||
let name = fixKeywordName(inp.name);
|
||||
|
||||
if (inp.array) {
|
||||
return `List<${toCSharpType(inp.type)}> ${inp.name}`;
|
||||
return `List<${toCSharpType(inp.type)}> ${name}`;
|
||||
} else {
|
||||
return `${toCSharpType(inp.type)} ${inp.name}`;
|
||||
return `${toCSharpType(inp.type)} ${name}`;
|
||||
}
|
||||
})
|
||||
.join(", ");
|
||||
@ -139,7 +161,7 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
a(
|
||||
2,
|
||||
`var param = new JsonArray(${fnc.inputs
|
||||
.map((e) => `JsonSerializer.SerializeToNode(${e.name})`)
|
||||
.map((e) => `JsonSerializer.SerializeToNode(${fixKeywordName(e.name)})`)
|
||||
.join(", ")});`
|
||||
);
|
||||
|
||||
@ -219,10 +241,11 @@ export class CSharpTarget extends CompileTarget<{ csharp_namespace: string }> {
|
||||
for (const fnc of definition.functions) {
|
||||
let params = [
|
||||
...fnc.inputs.map((inp) => {
|
||||
let name = fixKeywordName(inp.name)
|
||||
if (inp.array) {
|
||||
return `List<${toCSharpType(inp.type)}> ${inp.name}`;
|
||||
return `List<${toCSharpType(inp.type)}> ${name}`;
|
||||
} else {
|
||||
return `${toCSharpType(inp.type)} ${inp.name}`;
|
||||
return `${toCSharpType(inp.type)} ${name}`;
|
||||
}
|
||||
}),
|
||||
"TContext ctx",
|
||||
|
@ -1,6 +1,6 @@
|
||||
import chalk from "chalk";
|
||||
import { CompileTarget } from "../compile";
|
||||
import { TypeDefinition, EnumDefinition, ServiceDefinition, Step } from "../ir";
|
||||
import { TypeDefinition, EnumDefinition, ServiceDefinition, Step, IR } from "../ir";
|
||||
import { lineAppender, LineAppender } from "../utils";
|
||||
|
||||
const conversion = {
|
||||
@ -23,6 +23,16 @@ function toSnake(input: string) {
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: Add other keywords as well!
|
||||
const keywords = new Set(["type", "static"]);
|
||||
|
||||
const fixKeywordName = (name: string) => {
|
||||
if (keywords.has(name)) {
|
||||
return `${name}_`;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
name: string = "rust";
|
||||
|
||||
@ -71,17 +81,36 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
a(0, `#[derive(Clone, Debug, Serialize, Deserialize)]`);
|
||||
a(0, `pub struct ${definition.name} {`);
|
||||
for (const field of definition.fields) {
|
||||
a(1, `#[allow(non_snake_case)]`);
|
||||
|
||||
let fn = `pub ${field.name}:`;
|
||||
if (keywords.has(field.name)) {
|
||||
// TODO: Add other keywords as well!
|
||||
console.log(
|
||||
chalk.yellow("[RUST] WARNING:"),
|
||||
`Field name '${field.name}' is not allowed in Rust. Renaming to '${field.name}_'`
|
||||
);
|
||||
fn = `pub ${fixKeywordName(field.name)}:`;
|
||||
a(1, `#[serde(rename = "${field.name}")]`);
|
||||
}
|
||||
let opts = "";
|
||||
let opte = "";
|
||||
if (field.optional) {
|
||||
opts = "Option<";
|
||||
opte = ">";
|
||||
}
|
||||
|
||||
if (field.array) {
|
||||
a(1, `pub ${field.name}: Vec<${toRustType(field.type)}>,`);
|
||||
a(1, `${fn} ${opts}Vec<${toRustType(field.type)}>${opte},`);
|
||||
} else if (field.map) {
|
||||
a(
|
||||
1,
|
||||
`pub ${field.name}: HashMap<${toRustType(
|
||||
`${fn} ${opts}HashMap<${toRustType(
|
||||
field.map
|
||||
)}, ${toRustType(field.type)}>,`
|
||||
)}, ${toRustType(field.type)}>${opte},`
|
||||
);
|
||||
} else {
|
||||
a(1, `pub ${field.name}: ${toRustType(field.type)},`);
|
||||
a(1, `${fn} ${opts}${toRustType(field.type)}${opte},`);
|
||||
}
|
||||
}
|
||||
a(0, `}`);
|
||||
@ -101,7 +130,7 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
a(0, `#[repr(i64)]`);
|
||||
a(
|
||||
0,
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]"
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum)]"
|
||||
);
|
||||
a(0, `pub enum ${definition.name} {`);
|
||||
for (const field of definition.values) {
|
||||
@ -137,17 +166,18 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
a(0, ``);
|
||||
for (const fnc of definition.functions) {
|
||||
let params = fnc.inputs
|
||||
.map((i) => i.name + ": " + typeToRust(i.type, i.array))
|
||||
.map((i) => fixKeywordName(i.name) + ": " + typeToRust(i.type, i.array))
|
||||
.join(", ");
|
||||
let ret = fnc.return
|
||||
? typeToRust(fnc.return.type, fnc.return.array)
|
||||
: "()";
|
||||
a(1, `#[allow(non_snake_case)]`);
|
||||
a(1, `pub async fn ${fnc.name}(&self, ${params}) -> Result<${ret}> {`);
|
||||
a(2, `let l_req = JRPCRequest {`);
|
||||
a(3, `jsonrpc: "2.0".to_owned(),`);
|
||||
a(3, `id: None, // 'id' will be set by the send_request function`);
|
||||
a(3, `method: "${definition.name}.${fnc.name}".to_owned(),`);
|
||||
a(3, `params: json!([${fnc.inputs.map((e) => e.name)}])`);
|
||||
a(3, `params: json!([${fnc.inputs.map((e) => fixKeywordName(e.name))}])`);
|
||||
a(2, `};`);
|
||||
a(2, ``);
|
||||
if (fnc.return) {
|
||||
@ -200,12 +230,13 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
let params =
|
||||
fnc.inputs.length > 0
|
||||
? fnc.inputs
|
||||
.map((i) => i.name + ": " + typeToRust(i.type, i.array))
|
||||
.map((i) => fixKeywordName(i.name) + ": " + typeToRust(i.type, i.array))
|
||||
.join(", ")
|
||||
: "";
|
||||
let ret = fnc.return
|
||||
? typeToRust(fnc.return.type, fnc.return.array)
|
||||
: "()";
|
||||
a(1, `#[allow(non_snake_case)]`);
|
||||
a(1, `async fn ${fnc.name}(&self, ${params}) -> Result<${ret}>;`);
|
||||
}
|
||||
a(0, `}`);
|
||||
@ -216,6 +247,7 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
a(0, `impl ${definition.name}Handler {`);
|
||||
//TODO: Maybe add a new definition like, pub fn new2<T>(implementation: T) where T: ${definition.name} + Sync + Send + 'static {}
|
||||
a(
|
||||
1,
|
||||
`pub fn new(implementation: Box<dyn ${definition.name} + Sync + Send + 'static>) -> Arc<Self> {`
|
||||
@ -235,6 +267,7 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
a(1, `fn get_id(&self) -> String { "${definition.name}".to_owned() }`);
|
||||
a(0, ``);
|
||||
|
||||
a(1, `#[allow(non_snake_case)]`);
|
||||
a(
|
||||
1,
|
||||
`async fn handle(&self, msg: &JRPCRequest, function: &str) -> Result<(bool, Value)> {`
|
||||
|
@ -33,8 +33,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
}
|
||||
|
||||
private generateImport(imports: string, path: string) {
|
||||
return `import ${imports} from "${
|
||||
path + (this.flavour === "esm" ? ".ts" : "")
|
||||
return `import ${imports} from "${path + (this.flavour === "esm" ? ".js" : "")
|
||||
}";\n`;
|
||||
}
|
||||
|
||||
@ -89,7 +88,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
} else {
|
||||
type = toJSType(field.type);
|
||||
}
|
||||
return `${field.name}?: ${type}; `;
|
||||
return `${field.name}${field.optional ? "?" : ""}: ${type}; `;
|
||||
})
|
||||
);
|
||||
|
||||
@ -125,10 +124,18 @@ export class TypescriptTarget extends CompileTarget {
|
||||
);
|
||||
a(1, `let res = new ${def.name}() as any;`);
|
||||
def.fields.forEach((field) => {
|
||||
if (field.optional) {
|
||||
a(
|
||||
1,
|
||||
`if(data["${field.name}"] !== null && data["${field.name}"] !== undefined) {`
|
||||
);
|
||||
} else {
|
||||
a(
|
||||
1,
|
||||
`if(data["${field.name}"] === null || data["${field.name}"] === undefined) throw new VerificationError("${def.name}", "${field.name}", data["${field.name}"]);`
|
||||
);
|
||||
a(1, `else {`);
|
||||
}
|
||||
if (field.array) {
|
||||
a(
|
||||
2,
|
||||
@ -200,7 +207,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
this.writeFormattedFile(
|
||||
"service_client.ts",
|
||||
this.generateImport(
|
||||
"{ RequestObject, ResponseObject, ErrorCodes, Logging }",
|
||||
"{ type RequestObject, type ResponseObject, ErrorCodes, Logging }",
|
||||
"./service_base"
|
||||
) +
|
||||
this.generateImport(" { VerificationError }", "./ts_base") +
|
||||
@ -297,7 +304,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
this.writeFormattedFile(
|
||||
"service_server.ts",
|
||||
this.generateImport(
|
||||
"{ RequestObject, ResponseObject, ErrorCodes, Logging }",
|
||||
"{ type RequestObject, type ResponseObject, ErrorCodes, Logging }",
|
||||
"./service_base"
|
||||
) +
|
||||
this.generateImport(" { VerificationError }", "./ts_base") +
|
||||
@ -335,8 +342,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
`ctx: T`,
|
||||
].join(", ");
|
||||
const retVal = fnc.return
|
||||
? `Promise<${
|
||||
toJSType(fnc.return.type) + (fnc.return.array ? "[]" : "")
|
||||
? `Promise<${toJSType(fnc.return.type) + (fnc.return.array ? "[]" : "")
|
||||
}>`
|
||||
: `void`;
|
||||
a(1, `abstract ${fnc.name}(${params}): ${retVal};`);
|
||||
@ -381,8 +387,7 @@ export class TypescriptTarget extends CompileTarget {
|
||||
2,
|
||||
`return this.${fnc.name}.call(this, ...p)` + //TODO: Refactor. This line is way to compicated for anyone to understand, including me
|
||||
(fnc.return
|
||||
? `.then(${
|
||||
fnc.return?.array
|
||||
? `.then(${fnc.return?.array
|
||||
? `res => res.map(e => apply_${fnc.return.type}(e))`
|
||||
: `res => apply_${fnc.return.type}(res)`
|
||||
});`
|
||||
|
@ -4,6 +4,7 @@
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>10.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -11,10 +11,12 @@ public class JRpcClient
|
||||
{
|
||||
private JRpcTransport Transport;
|
||||
private IDictionary<string, TaskCompletionSource<JsonNode?>> Requests;
|
||||
private int? Timeout = null;
|
||||
|
||||
public JRpcClient(JRpcTransport transport)
|
||||
public JRpcClient(JRpcTransport transport, int? timeout = null)
|
||||
{
|
||||
this.Transport = transport;
|
||||
this.Timeout = timeout;
|
||||
this.Requests = new Dictionary<string, TaskCompletionSource<JsonNode?>>();
|
||||
|
||||
this.Transport.OnPacket += this.HandlePacket;
|
||||
@ -87,10 +89,43 @@ public class JRpcClient
|
||||
|
||||
var task = new TaskCompletionSource<JsonNode?>();
|
||||
this.Requests.Add(id, task);
|
||||
await this.Transport.Write(request.ToJsonString());
|
||||
|
||||
try
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await this.Transport.Write(request.ToJsonString());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
task.SetException(e);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.Timeout.HasValue)
|
||||
{
|
||||
if (await Task.WhenAny(task.Task, Task.Delay(this.Timeout.Value)) == task.Task)
|
||||
{
|
||||
return await task.Task;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new JRpcTimeoutException();
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
return await task.Task;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.Requests.Remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<TResult?> SendRequest<TResult>(string method, JsonArray param)
|
||||
{
|
||||
@ -128,3 +163,8 @@ public class JRpcException : Exception
|
||||
{
|
||||
public JRpcException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public class JRpcTimeoutException : JRpcException
|
||||
{
|
||||
public JRpcTimeoutException() : base("Request Timeout") { }
|
||||
}
|
||||
|
@ -6,11 +6,10 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
int-enum = "0.5.0"
|
||||
int-enum = { version ="0.5.0", features = ["serde", "convert"] }
|
||||
serde = { version = "1.0.147", features = ["derive"] }
|
||||
serde_json = "1.0.88"
|
||||
nanoid = "0.4.0"
|
||||
tokio = { version = "1.22.0", features = ["full"] }
|
||||
log = "0.4.17"
|
||||
simple_logger = { version = "4.0.0", features = ["threads", "colored", "timestamps", "stderr"] }
|
||||
async-trait = "0.1.59"
|
||||
|
@ -40,7 +40,7 @@ pub struct JRPCError {
|
||||
pub struct JRPCResult {
|
||||
pub jsonrpc: String,
|
||||
pub id: String,
|
||||
pub result: Value,
|
||||
pub result: Option<Value>,
|
||||
pub error: Option<JRPCError>,
|
||||
}
|
||||
|
||||
@ -76,8 +76,11 @@ impl JRPCClient {
|
||||
if let Some(result) = result {
|
||||
if let Some(error) = result.error {
|
||||
return Err(format!("Error while receiving result: {}", error.message).into());
|
||||
} else if let Some(result) = result.result {
|
||||
return Ok(result);
|
||||
} else {
|
||||
return Ok(result.result);
|
||||
return Ok(Value::Null);
|
||||
// return Err(format!("No result received").into());
|
||||
}
|
||||
} else {
|
||||
return Err("Error while receiving result".into());
|
||||
@ -133,7 +136,7 @@ impl JRPCSession {
|
||||
let result = JRPCResult {
|
||||
jsonrpc: "2.0".to_string(),
|
||||
id: request_id,
|
||||
result: Value::Null,
|
||||
result: None,
|
||||
error: Some(error),
|
||||
};
|
||||
|
||||
@ -169,7 +172,7 @@ impl JRPCSession {
|
||||
.send(JRPCResult {
|
||||
jsonrpc: "2.0".to_string(),
|
||||
id: request.id.unwrap(),
|
||||
result,
|
||||
result: Some(result),
|
||||
error: None,
|
||||
})
|
||||
.await;
|
||||
|
@ -1,14 +1,22 @@
|
||||
function form_verficiation_error_message(type?: string, field?: string) {
|
||||
let msg = "Parameter verification failed! ";
|
||||
if (type && field) {
|
||||
msg += `At ${type}.${field}! `;
|
||||
} else if (type) {
|
||||
msg += `At type ${type}! `;
|
||||
} else if (field) {
|
||||
msg += `At field ${field}! `;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
export class VerificationError extends Error {
|
||||
constructor(
|
||||
public readonly type?: string,
|
||||
public readonly field?: string,
|
||||
public readonly value?: any
|
||||
) {
|
||||
super(
|
||||
"Parameter verification failed! " +
|
||||
(type ? "Expected " + type + "! " : "") +
|
||||
(field ? "At: " + field + "! " : "")
|
||||
);
|
||||
super(form_verficiation_error_message(type, field));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
//@template-ignore
|
||||
import { VerificationError } from "./ts_base";
|
||||
//@template-ignore
|
||||
import { RequestObject, ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||
import { type RequestObject, type ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||
|
||||
|
||||
export type IMessageCallback = (data: any) => void;
|
||||
|
@ -1,7 +1,7 @@
|
||||
//@template-ignore
|
||||
import { VerificationError } from "./ts_base";
|
||||
//@template-ignore
|
||||
import { RequestObject, ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||
import { type RequestObject, type ResponseObject, ErrorCodes, Logging } from "./ts_service_base";
|
||||
|
||||
|
||||
export class Service<T> {
|
||||
|
Reference in New Issue
Block a user