DEV Community

loading...

DEV Api a practical use case of streams

artydev profile image artydev ・2 min read

For fun here is a simple example using streams, no framework, vanilla JS

You can test it here DEV API

function stream(v) {
    let mappers = []
    let storedvalue = v

    function _stream(v = storedvalue) {
        if (v) storedvalue = v;
        mappers.map((f) => v && f(v))
        return storedvalue;
    }
    _stream.map = function(f) {
        mappers.push(f)
    }
    return _stream
}

let currentusr = "artydev"

const users = ["artydev", "dailydevtips1"]

// search user from input box
window.searchInput = () => {
    user(searchuser.value);
    currentusr = searchuser.value
}

// search user from list
window.searchUser = (usr) => {
    user(usr);
    currentusr = usr
}

// url API
function url(user) {
    return `https://dev.to/api/articles?username=${user}&per_page=1000`
}

function listUsers() {
    return `
    <ul style="text-align:left; margin-left: 10px; margin-top:10px;">
      ${users.map(u => `<li class="user" onclick="searchUser('${u}')">${u}</li>`).join("")}
    </ul>
  `
}

async function getPosts(user) {
    const response = await fetch(url(user))
    const json = await response.json()
    return json
}

function inputSearch() {
    return `<input id="searchuser" />
  `
}

function displayPost(post) {
    return `
    <li class="post">
      <div class="headpost">
        <a href="${post.url}">${post.title}</a>
      </div>
      <div class="description">
        <em>${post.description}</em>
      </div>
    </li>
  `
}

function listPosts(posts) {
    const view = `
    <ul>
      ${posts.map(displayPost).join('')}
    </ul>
  `
    return view
}

function App(posts) {
    document.body.innerHTML = `
    <div class="title">
      <h3>Dev to Posts  -  ${currentusr} ${posts.length}  articles </h3>
    </div>
    <div class="searchbar">
        <div>
          ${inputSearch()}
          <button onclick="searchInput()">search user posts</button>
        </div>
      </div>
    <div class="container">
      <div>${listPosts(posts)}</div>
      <div class="users">
        <h4>Users</h4>
        <div>${listUsers()}</div>
    </div>
  `
}

const user = stream()

user.map((usr) => {
    console.log(usr)
    getPosts(usr).then(App)
})

user(currentusr)

Discussion (0)

pic
Editor guide