Using protobuf in Vue

json online editor: https://www.89tool.com/ 

json转protobuf:https://www.89tool.com/json/json2protobuf

Protobuf is a language-independent and platform-independent, extensible serialization data structure protocol launched by Google, similar to XML, but smaller, faster and simpler than XML. protobuf supports almost most of the current languages, such as JavaScript 

Install protobufjs

cnpm i -S protobufjs

Note: The current version of protobufjs is: 6.11.2 

 Create a new proto directory in the project src directory , and put the test.proto file given by the backend into it

syntax = "proto3";//第一行指定了正在使用proto3语法:如果你没有指定这个,编译器会使用proto2。这个指定语法行必须是文件的非空非注释的第一行

message User {
  required string username = 0;
  required double password = 1;
  required bool isMan = 2;

  message OTHER {
    required double score = 0;
    required string address = 1;
  }

  required OTHER other = 3;

  message FRIENDS {
    required string name = 0;
    required double age = 1;
  }

  repeated FRIENDS friends = 4;
}

Open the dos window and execute the following command to convert the proto file into a js file. It takes about 15 seconds to execute. After successful execution, the proto.js file will be created in the src/proto folder

npx pbjs -t json-module -w commonjs -o src/proto/proto.js src/proto/*.proto

注意:-wThe parameter can specify a wrapper for packaging js, here is commonjs. In addition to generating js files, .proto files can also generate json files. It is usually easier to package as a js module, because vue only has html, css, js and other files after being packaged in the production environment. The command to generate the json file is:

npx pbjs -t json src/proto/*.proto > src/proto/proto.json

/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/
"use strict";

var $protobuf = require("protobufjs/light");

var $root = ($protobuf.roots["default"] || ($protobuf.roots["default"] = new $protobuf.Root()))
.addJSON({
  User: {
    fields: {
      username: {
        rule: "required",
        type: "string",
        id: 0
      },
      password: {
        rule: "required",
        type: "double",
        id: 1
      },
      isMan: {
        rule: "required",
        type: "bool",
        id: 2
      },
      other: {
        rule: "required",
        type: "OTHER",
        id: 3
      },
      friends: {
        rule: "repeated",
        type: "FRIENDS",
        id: 4
      }
    },
    nested: {
      OTHER: {
        fields: {
          score: {
            rule: "required",
            type: "double",
            id: 0
          },
          address: {
            rule: "required",
            type: "string",
            id: 1
          }
        }
      },
      FRIENDS: {
        fields: {
          name: {
            rule: "required",
            type: "string",
            id: 0
          },
          age: {
            rule: "required",
            type: "double",
            id: 1
          }
        }
      }
    }
  }
});

module.exports = $root;

 Import proto.js:

import protoRoot from "@/proto/proto.js";

First print to see the protoRoot content:

 

Basic use:

<template>
  <div class="main"></div>
</template>
<script>
import protoRoot from "@/proto/proto.js";
export default {
  mounted() {
    let testobj = protoRoot.lookup("User").create({
      username: "lijiang",
      isMan: true,
      other: {
        score: 90.23,
        address: "四川",
      },
      friends: [
        {
          name: "张三",
          age: 23,
        },
        {
          name: "lisi",
          age: 22.5,
        },
      ],
    });
    testobj.password = 123; //还可以以这种方式赋值
    console.log("testobj:", testobj);
    let testObjBuffer = protoRoot.lookup("User").encode(testobj).finish(); //encode数据
    console.log("testObjBuffer:", testObjBuffer);
    let testdata = protoRoot.lookup("User").decode(testObjBuffer); //decode数据
    console.log("testdata:", testdata);
  },
};
</script>

 For future convenience, we can add the command to the script of package.json:

"proto": "pbjs -t json-module -w commonjs -o src/proto/proto.js  src/proto/*.proto"

After updating the proto file in the future, you only need npm run prototo regenerate the latest proto.js

Note: When using axios to initiate a request, you need to pay attention to setting the request type of axios to use arraybuffer:

import axios from 'axios'
const httpService = axios.create({
  timeout: 45000,
  method: 'post',
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/octet-stream'
  },
  responseType: 'arraybuffer'
})

Possible errors:

When using ' json to protobuf online editor ', it is necessary to pay attention to the semicolon at the end of each line manually added to the converted protobuf, as follows:

In addition, after generating proto.js, be sure to remember to check whether each field is consistent, especially case and underscore! 

Guess you like

Origin blog.csdn.net/qq_40323256/article/details/123809155