diff --git a/backend-assemblyscript/step3-finished-app/assembly/main.ts b/backend-assemblyscript/step3-finished-app/assembly/main.ts index da680b0..f077d6a 100644 --- a/backend-assemblyscript/step3-finished-app/assembly/main.ts +++ b/backend-assemblyscript/step3-finished-app/assembly/main.ts @@ -1,5 +1,5 @@ import {Action, decode, FetchRequest, PostRequest} from "./request"; -import {PostResponse, UnknownResponse} from "./response"; +import {decodePosts, PostResponse, UnknownResponse} from "./response"; import {addMessage, createScheme, getMessages, getPostsCount} from "./model"; createScheme(); @@ -20,7 +20,9 @@ export function handler(input: string): string { let fetch = request as FetchRequest; let result = getMessages(fetch.username); - return result; + + let response = decodePosts(result); + return response.serialize(); } let response = new UnknownResponse(); diff --git a/backend-assemblyscript/step3-finished-app/assembly/response.ts b/backend-assemblyscript/step3-finished-app/assembly/response.ts index feef24e..4bd4009 100644 --- a/backend-assemblyscript/step3-finished-app/assembly/response.ts +++ b/backend-assemblyscript/step3-finished-app/assembly/response.ts @@ -1,4 +1,6 @@ import {JSONEncoder} from "../node_modules/assemblyscript-json/assembly/encoder"; +import {JSONDecoder, JSONHandler} from "../node_modules/assemblyscript-json/assembly/decoder"; +import {string2Bytes} from "./request"; export abstract class Response { serialize(): string { @@ -50,6 +52,46 @@ export class PostResponse extends Response { } } +class PostsJSONEventsHandler extends JSONHandler { + + public messages: Array = new Array(); + message: string | null; + username: string | null; + + setString(name: string, value: string): void { + + if (name == "message") { + this.message = value; + } else if (name == "username") { + this.username = value; + } + } + + pushObject(name: string): bool { + this.message = null; + this.username = null; + return true; + } + + popObject(): void { + let message = new Message(this.message as string, this.username as string); + this.messages.push(message) + } +} + + export function decodePosts(input: string): FetchResponse { + let jsonHandler = new PostsJSONEventsHandler(); + let decoder = new JSONDecoder(jsonHandler); + + let bytes = string2Bytes(input); + + decoder.deserialize(bytes); + + let messages = jsonHandler.messages; + + return new FetchResponse(messages); +} + export class FetchResponse extends Response { posts: Array;