garrettmac
7/1/2017 - 6:27 PM

Reddit API using AXIOS

Reddit API using AXIOS

import axios from 'axios';
import _ from 'lodash';

let count=0;
let limit=0;
let after=0;

// create reddit axios const
const redditAPI = axios.create({
	baseURL:`${window.location.protocol}//reddit.com`,
	responseType: "json",
	timeout: 3000,
	// headers: { 'User-Agent': `${ Platform.OS }:${ appId }:1.0.0 (by /u/vygaio)` }
})





//get posts
const getPosts = () => {
  //if(!_.startsWith(window.location.protocol,"http"))
  return redditAPI(`/api/info.json?jsonp&url=${window.location.href}`)
          .then((o)=>_.get(o, 'data.data.children', []).map(p=>p.data))
};


//get comments
const getComments=(p,limit=10,after=0,count=0)=>{
  return redditAPI(`${p.permalink}.json?&limit=${limit}&after=${after}&count=${count}`)
            .then(c=>_.get(c, 'data[1].data.children', []).map(c=>c.data)
}



getPosts.then(p=>getComments(p))
import { Platform } from 'react-native'
import axios from 'axios'
import _ from 'lodash'
import subreddits from '../../subreddits'
import { extendObservable, action, observable } from 'mobx'
import normalizeUrl from 'normalize-url'

const appId = Platform.select({
  ios: 'io.vyga.[APP NAME HERE]',
  android: 'io.vyga.[APP NAME HERE]'
})

export default state => {

  function getUrl(endpoint, paged = true) {
    const { after, count } = state.reddit

    const pagingParams = `&limit=10&after=${ after }&count=${ count }`
    const requestUrl = `https://www.reddit.com/r/${endpoint}/top.json?nsfw=0&sort=top&t=day`

    return requestUrl + (paged ? pagingParams : '')
  }

  function getPosts(paging = true) {
    const subredditsStr = subreddits.join('+')

    return axios
      .get(getUrl(subredditsStr, paging), {
        headers: { 'User-Agent': `${ Platform.OS }:${ appId }:1.0.0 (by /u/[username])` }
      })
      .then(({ data }) => parsePostsFromData(data))
  }

  function parsePostsFromData(data) {
    const posts = _.get(data, 'data.children', [])

    if(!posts.length) {
      return getPosts(false)
    }

    return _.chain(posts)
      .map(post => post.data)
      .filter(post => (
        post.over_18 === false &&
        post.is_self === false &&
        post.post_hint === 'link'
      ))
      .map(post => Object.assign({}, post, { url: normalizeUrl(_.get(post, 'url', 'no://url')) }))
      .uniqBy('url')
      .value()
  }

  return {
    getPosts
  }
}