美文网首页
第四课 motoko源码

第四课 motoko源码

作者: Limit_ | 来源:发表于2022-01-26 13:36 被阅读0次
    import List "mo:base/List";
    import Iter "mo:base/Iter";
    import Time "mo:base/Time";
    import Principal "mo:base/Principal";
    actor {
        public type Message = {
            content: Text;
            time: Time.Time;
        };
        public type Microblog = actor {
            follow: shared(Principal) -> async (); //添加关注对象
            follows: shared query () -> async ([Principal]);//返回关注列表
            post: shared (Text) -> async (); //发布新消息
            posts: shared query () -> async [Message]; //返回所有发布的新消息
            timeline: shared () -> async [Message]; //返回所有关注对象发布的消息
        };
        stable var followed : List.List<Principal> = List.nil();
    
        public shared func follow(id: Principal) :async () {
            followed := List.push(id, followed);
        };
        public shared  query func follows() : async [Principal] {
            List.toArray(followed)
        };
    
        stable var messages : List.List<Message> = List.nil();
    
        public shared(msg) func post(content: Text) : async (){
            //assert(Principal.toText(msg.caller) == "t5f3o-4jc2c-kedu6-zkclt-jygbq-llpj7-o5sjc-nlwal-l6mis-zk4mq-jae");
            let message : Message = {
                content = Principal.toText(msg.caller);
                time = Time.now();
            };
            messages := List.push(message, messages);
        };
        public shared query func posts(since: Time.Time): async [Message] {
            var all:List.List<Message> = List.nil();
            for(msg in Iter.fromList(messages)) {
                if(msg.time > since) {
                    all := List.push(msg, all);
                }
            };
            List.toArray(all);
        };
        public shared func timeline(since: Time.Time) : async [Message] {
            var all:List.List<Message> = List.nil();
            for(id in Iter.fromList(followed)) {
                let canister : Microblog = actor(Principal.toText(id));
                let msgs = await canister.posts();
                for(msg in Iter.fromArray(msgs)) {
                   if(msg.time > since) {
                        all := List.push(msg, all);
                    }; 
                }
            };
            List.toArray(all);
        };
    };
    
    

    相关文章

      网友评论

          本文标题:第四课 motoko源码

          本文链接:https://www.haomeiwen.com/subject/yqjnhrtx.html