flatbuffers 代码集成

参考上次的操作,因为默认的不是nodejs 模块友好的,使用了typescript 同时集成了代码

schema

union HttpCommand {
    HttpQuery,
    HttpResultSet,
    HttpError
}
 
table HttpMessage {
    message_id: uint;
    command: HttpCommand;
}
 
table HttpQuery {
    query: string;
}
 
table HttpError {
    error: string;
}
 
table HttpResultSet {
    columns: [string];
    rows: [HttpRow];
}
 
table HttpRow {
    values: [HttpColumnValue];
}
 
table HttpColumnValue {
    string_value: string;
}
root_type HttpMessage;

生成代码

flatc --ts http_message.fbs

生成nodejs 模块友好的代码

使用tsc 编译

{
  "name": "first",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "flatbuffers": "^1.12.0"
  },
  "scripts": {
    "watch": "tsc --watch"
  },
  "devDependencies": {
    "@types/flatbuffers": "^1.10.0",
    "typescript": "^4.2.3"
  }
}

代码集成

const flatbuffers = require("flatbuffers").flatbuffers
const {HttpQuery,HttpMessage,HttpCommand} = require("./http_message_generated")
const builder = new flatbuffers.Builder(1024);
const queryOffset = builder.createString("dalongrong");
const httpQueryOffset = HttpQuery.createHttpQuery(builder,queryOffset);
const messageId = 10000
const message = HttpMessage.createHttpMessage(builder, messageId, HttpCommand.HttpQuery, httpQueryOffset);
builder.finish(message);
let msg =builder.asUint8Array()
const buf = new flatbuffers.ByteBuffer(msg);
const myHttpMessage = HttpMessage.getRootAsHttpMessage(buf);
console.log("command:",myHttpMessage.commandType())
if (myHttpMessage.commandType()==HttpCommand.HttpQuery){
    const httpQuery = myHttpMessage.command(new HttpQuery());
    console.log("query:",httpQuery.query())
}

运行效果

 

 

参考资料

https://google.github.io/flatbuffers/flatbuffers_guide_use_typescript.html
https://google.github.io/flatbuffers/flatbuffers_guide_using_schema_compiler.html

posted on 2021-03-28 23:06  荣锋亮  阅读(202)  评论(0编辑  收藏  举报

导航