parse posts from db

This commit is contained in:
DieMyst
2019-08-17 20:15:34 +03:00
parent 5b00e0ed96
commit e71e01dde5
2 changed files with 46 additions and 2 deletions

View File

@ -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();

View File

@ -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<Message> = new Array<Message>();
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<PostsJSONEventsHandler>(jsonHandler);
let bytes = string2Bytes(input);
decoder.deserialize(bytes);
let messages = jsonHandler.messages;
return new FetchResponse(messages);
}
export class FetchResponse extends Response {
posts: Array<Message>;