Little Present: Allittle API for the API

// My cute write.as - API-API
class postAPI {

  //constructor, give collection and authorization
  constructor(blog, user, pass) {
    this.token= null;
    this.arts= null;
    this.tags = null;

    this.user= user;
    this.pass= pass;

    this.apihost = "https://corsproxy.io/?https://write.as";
    this.blog = blog;
    
    this.semaphore = true;
  }////////////////////////////////////

  // Authenticate the API, get a token
  async authAPI() {
    //just authenticated ?
    if (this.token) return;

    //use fetch to post our login data
    const response = await fetch(this.apihost + 
                                 '/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
       },
       body: JSON.stringify( {'alias' : this.user, 
                              'pass' : this.pass} )
     });

     //create a json from response
     const data = await response.json();

     //set our token
     this.token = data.data.access_token;
  } /////////////////////////////////////////////////

  // Get all posts for my blog
  async getPosts() {
    // authenticate first
    await this.authAPI();

    //just arts are empty?
    if (this.arts) return;

    //use fetch to post our login data
    const response = await fetch(this.apihost +
                                 '/api/me/posts', {
      method: 'GET',
      headers: {
        'Authorization': 'Token ' + this.token,
        'Content-Type': 'application/json'
       }
     });

     //create our response JSON
     const data = await response.json();
     //prepare arts array
     this.arts = [];

     data.data.forEach((post, index, posts) => {
       if (post.collection && 
           post.collection.alias &&
           post.collection.alias == this.blog)
          this.arts.push(post);
     });

     //now lets get our tags
     this.getTags();
     
     return Promise.resolve(1);
  }////////////////////////////////////////

  //Get all Tags we use in the posts
  getTags() {
    //just tags are empty?
    if (this.tags) return;

    // Do we have all posts complete here?
    if (! this.arts) return false;

    //Prepare scalar
    this.tags = [];
    
    this.arts.forEach((article, index, arts) => { 
      article.tags.forEach((tag, tindex, tags) => {
          //get the array for this tag
          
          let tagposts = this.tags.some((elem) => elem.tagname == tag) ? 
                           this.tags.find((elem) => elem.tagname == tag) :
                           {tagname: tag, posts: []};
          tagposts.posts.push(article);
          
          if (this.tags.some((elem) => elem.tagname == tag))
            //save the array of articles for this tag
            this.tags[this.tags.findIndex((elem) => 
                                           elem.tagname == tag)] = tagposts;
          else
            //append the tagposts object
            this.tags.push(tagposts);
      });
    });

    //Now we have our posts and tags, lets sortTags
    this.sortTags();
    this.sortTagsPosts();
  }//////////////////////////////////////////////////////////

  //Sorts the taglist by name of the tags, ascending
  sortTags() {
    this.tags.sort((taga, tagb) => {
      let fa = taga.tagname.toLowerCase(),
          fb = tagb.tagname.toLowerCase();

      if (fa < fb) return -1;
      
      if (fa > fb) return 1;
      
      return 0;
    });
  }/////////////////////////////////////////////////////////

  //Sorts all arrays of posts in the tags array, 
  //depending on update time, ascending
  sortTagsPosts() {
    this.tags.forEach((tagposts, index, tags) => {
      tagposts.posts.sort((taga, tagb) => {
        let da = new Date(taga.created),
            db = new Date(tagb.created);
        return da - db;
      });
    });
  }/////////////////////////////////////////////////////////

  //Sort the list of posts by updated-time
  sortPostsUpdated() {
    this.arts.sort((taga, tagb) => {
      let da = new Date(taga.updated),
          db = new Date(tagb.updated);
      return da - db;
    });
  }/////////////////////////////////////////////////////////
  
  //Sort the list of posts by updated-time
  sortPostsCreated() {
    this.arts.sort((taga, tagb) => {
      let da = new Date(taga.created),
          db = new Date(tagb.created);
      return da - db;
    });
  }/////////////////////////////////////////////////////////

  //returns an array with article objects
  getArticlesList() {
    return this.arts;
  }/////////////////////////////////////////////////////////

  //returns an array of objects {tagname: "sometagname", posts: [article1, article2, ..]}
  getTagsList() {
    return this.tags;
  }//////////////////////////////////////////////////////////

}

var myapi = new postAPI("nameoftheblog", 
                                "user", 
                                "password");


myapi.getPosts().then(parsePage);

parsePage() is a function where you can myapi the use. This little API get your posts, sort them, get your tags.

Much fun with my little present for the community,

dietrich

1 Like