1
0
mirror of https://github.com/fluencelabs/fluid synced 2025-04-08 05:08:28 +00:00

91 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-08-14 16:35:24 +03:00
import {JSONDecoder, JSONHandler} from "../node_modules/assemblyscript-json/assembly/decoder";
export enum Action {
Post,
Fetch,
Unknown
2019-08-16 12:27:30 +03:00
// Error
2019-08-14 16:35:24 +03:00
}
export abstract class Request {
public action: Action = Action.Unknown;
}
export class PostRequest extends Request {
2019-08-16 19:47:38 +03:00
public readonly message: string;
2019-08-15 19:10:13 +03:00
public readonly username: string;
2019-08-14 16:35:24 +03:00
2019-08-16 19:47:38 +03:00
constructor(message: string, username: string) {
2019-08-14 16:35:24 +03:00
super();
2019-08-16 19:47:38 +03:00
this.message = message;
2019-08-15 19:10:13 +03:00
this.username = username;
2019-08-14 16:35:24 +03:00
this.action = Action.Post;
}
}
export class FetchRequest extends Request {
2019-08-16 12:27:30 +03:00
public readonly username: string | null;
constructor(username: string | null) {
2019-08-14 16:35:24 +03:00
super();
this.action = Action.Fetch;
2019-08-16 12:27:30 +03:00
this.username = username;
2019-08-14 16:35:24 +03:00
}
}
export class UnknownRequest extends Request {
constructor() {
super();
this.action = Action.Unknown;
}
}
2019-08-16 12:27:30 +03:00
export function string2Bytes(str: string): Uint8Array {
2019-08-14 16:35:24 +03:00
return Uint8Array.wrap(String.UTF8.encode(str));
}
export function decode(input: string): Request {
let jsonHandler = new RequestJSONEventsHandler();
let decoder = new JSONDecoder<RequestJSONEventsHandler>(jsonHandler);
let bytes = string2Bytes(input);
decoder.deserialize(bytes);
let action = jsonHandler.action;
let request: Request;
if (action == "Fetch") {
2019-08-16 12:27:30 +03:00
request = new FetchRequest(jsonHandler.filter_handle);
2019-08-14 16:35:24 +03:00
} else if (action == "Post") {
2019-08-16 19:47:38 +03:00
request = new PostRequest(jsonHandler.message, jsonHandler.username)
2019-08-14 16:35:24 +03:00
} else {
request = new UnknownRequest()
}
return request;
}
class RequestJSONEventsHandler extends JSONHandler {
public action: string;
2019-08-16 19:47:38 +03:00
public message: string;
2019-08-15 19:10:13 +03:00
public username: string;
2019-08-16 12:27:30 +03:00
public filter_handle: string | null;
2019-08-14 16:35:24 +03:00
setString(name: string, value: string): void {
if (name == "action") {
this.action = value;
2019-08-16 19:47:38 +03:00
} else if (name == "message") {
this.message = value;
2019-08-15 19:10:13 +03:00
} else if (name == "username") {
this.username = value;
2019-08-16 12:27:30 +03:00
this.filter_handle = value;
2019-08-14 16:35:24 +03:00
}
// json scheme is not strict, so we won't throw an error on excess fields
}
}