Automatically generate Proto JS statements

Source: Internet
Author: User

When communicating with WebSocket on the back end, it is a chore to bring a proto file to the front end. The first is the obvious exposure of the protocol entity object, and then a browser client can easily cache the file, the new protocol update may cause the client to be unable to use, in addition to the CDN server also need to configure. The proto type client can download the past. Really legacy, they use the time will pay attention to these, but to others use when it is not optimistic, so this time all the proto files into JavaScript objects, eliminating the protocol files and loading steps.

Look at the code first:

 functionCreateproto (name) {varargs = [].slice.call (arguments, 1); varobj =NewProtobuf.        Type (name);  for(vari = 0; i < args.length; i++) {            varp =Args[i]; varKey = i + 1; Obj.add (NewProtobuf. Field (P[0], key, p[1] | | "String")); }        returnobj; }    functionCreateenum (name,list) {varobj =NewProtobuf.        Enum (name);  for(vari = 0; i < list.length; i++) {obj.add (list[i],i); }        returnobj; }    functionLoadproto (callback) {if(typeofProtobuf = = "undefined")return;//indicates that the browser failed to loadRoot=NewProtobuf. Root (). Define ("Imentity"); Root.add (Createproto ("Token", ["UserID"], ["token"], ["Device"], ["Version", "Int32"], ["Appkey"])); Root.add (Createproto ("Feedback", ["ResultCode", "Int32"], ["Resultdata"], ["Seq", "Int32"], ["MsgID"]));Root.add (Createenum ("Receipttype", ["Receive", "Read"]));
//...
Util.triggercallback (callback);};

There are two main types of proto, type and enum. The type corresponds to the message in the Protocol, which is equivalent to a class. Enum is enum type

var Root  = protobuf. Root,    Type  = protobuf. Type,    = protobuf. Field; var New Type ("Awesomemessage"). Add (new Field ("Awesomefield", 1, "string")); var New Root (). Define ("Awesomepackage"). Add (Awesomemessage);

Do not need field to create an enumeration. Only add field names are required. Then the next question is, handwriting root.add is also very annoying, because to a control property, constantly copy and paste, it is easy to make mistakes. So I made a page that generated the code automatically:

<textarea id= "Content" >//Login Tokenmessage token{string UserID= 1;//Imuserid returned by the login interfacestring Token = 2;//token returned by the login interfacestring Device = 3;//Client Device numberInt32 Version = 4;//version number, pre-release and service-side contract valuesstring Appkey = 5;//Client Appkey        }               //Receive private Messagesmessage receiveprivatemessage{string MsgID= 1;//Message IDstring SenderID = 2;//Sender IDstring receiverid = 3;//Recipient IDString Content = 4;//The message content. After the client is converted into a business-related entity, the subsequent processing (client use, server does not do any processing, issued as is)BOOL Ack = 5;//whether a read receipt is requiredInt32 senddatetime = 6;//Message Send TimeInt32 ContentType = 7;//Content Type (client use, server does not do any processing, issued as is)        }        //Receipt Typeenum receipttype{Receive= 0;//retracted (receipts sent to the server immediately after receiving the message)Read = 1;//read receipts (receipts sent to the server after the user enters the message reading interface)        }    </textarea> <div id= "result" ></div> <script>functionStart () {$ ("#result"). HTML (""); $("#result"). Append (' root = new protobuf. Root (). Define ("Improtoentity") <br> '); varReg =/("([^\\\"]* (\ \)?) *")| (' ([^\\\ ']* (\ \)?) * ') | (\/{2,}.*?) (\r|\n)) | (\/\* (\n|.) *?\*\/)/g,//Filter Commentsstr = $ (' #content '). Val ();//text you want to work with            //Console.log (Str.match (reg));//print out: matching substring            varNews = Str.replace (Reg, ""); //Console.log (news);//Print out: Original text            varREG1 =/[message|enum].*? {/mg; varRegobj =/{[^}{]*?} /g;//New Address            varNames =News.match (REG1); varProtos =News.match (regobj); //Console.log (names, protos);            varRoot = {};  for(vari = 0; i < names.length; i++) {                varRawname =Names[i]; varRawobj =Protos[i]; //if (~rawname.indexof ("message"))                if(!rawobj)Continue; varName = Rawname.replace ("{", ""). Replace ("message", ""). Replace ("enum", "); varobj ={name:name}; if(~rawname.indexof ("enum") ) {obj["type"] = "enum"; } rawobj= Rawobj.replace ("{", ""). Replace ("}", "'); varProtolist = Rawobj.split ('; ')); //Console.log ("Protolist", protolist);                varPlist = [];  for(varj = 0; J < Protolist.length; J + +) {                    varp =$.trim (Protolist[j]); if(p) {varargs = []; varList = P.split (' '); //console.log ("list", list);List.foreach (function(n) {n&&Args.push (n); }),                        //console.log ("args", args);Plist.push (args); }} obj.list=plist;                Console.log (obj);            Toproto (obj);        }} start (); functionToproto (obj) {varroot = "root"; varFun = "Createproto"; varEnumfun = "Createenum"; varstr = root + '. Add ('; varargs; if(!obj.type) {//messageargs = ";  for(vari = 0; i < obj.list.length; i++) {                    varitem =Obj.list[i]; //Old Protocol 2.0                    if(Item[0] = = "Required" | | item[0] = = "optional") {item.shift (); }                    //New Protocol 3.0                    if(item[0]! = "string") {args+ = ' [' + item[1] + ' "," ' + item[0] + ' "]; } Else{args+ = ' [' + item[1] + ' "] '; }                    if(I < obj.list.length-1) args + = ","; }            } Else{//enumargs = ' [';  for(vari = 0; i < obj.list.length; i++) {                    varitem =Obj.list[i]; Args+ = ' "' + item[0] + '" '; if(I < obj.list.length-1) args + = ","; } args+ = '] '; }            varall = str + (obj.type enumfun:fun) + ' ("' + Obj.name + '", ' + args + ')); '; //Console.log (all);$ ("#result"). Append (All + "<br>")); }    </script>

The page will then get:

The red part is copied into the project and can be used. Of course, take Createproto and Createenum two ways. Proto format to standardize, after all, start inside is split with a space. The way is much better than protobuf.load ("Xx.proto", callback). Load is more rigid in location requirements, be sure to be in the root directory. And the type does not exist will be an error, terminate the program. The Add method does not have an error that the type cannot be found. In addition, the speed is much faster.

Automatically generate Proto JS statements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.