Skip to content

nickpeihl/realworld-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

realworld-api

RealWorld library for open API calls using JavaScript

about

RealWorld is a fullstack Medium clone that can be written using many different web frameworks. It was developed as a way to show how to accomplish the same website using different backend and frontend technologies.

I created this module as a simple way to interact with the RealWorld API Specification which could be easily dropped in to any frontend technology stack.

Each public function is well-documented in the code using JSDoc and the documentation can be automatically generated using documentation.js.

Unit tests are written to be isolated and idempotent. Addtionally, you do not have to be connected to the internet in order to run the tests. The tests run on an ephemeral local Node.js HTTP server and ensure the API requests are correct.

realworld-api mostly follows the logic of the Tiny Guide to Non Fancy Node, however it makes use of template literals from ES6. If you are bundling realworld-api for use in an older browser that doesn't support template literals, you may want to compile your code using Babel or use a browserify transform such as ES2020.

install

npm install realworld-api

usage

var RealWorld = require('realworld-api')

var client = new RealWorld()

client.getArticles(function (err, res, data) {
  if (err) throw err
  console.log(data)
})

api

RealWorld

Realworld library for open API calls using JavaScript

Parameters

  • opts Object? options for configuring API
    • opts.token string authentication token from RealWorld (optional, default null)
    • opts.apiRoot string the url to Realworld API (optional, default https://conduit.productionready.io/api)

Examples

var client = new RealWorld()
var client = new RealWorld({
  apiRoot: 'http://localhost:8000/api',
  token: 'my-secret-authentication-token'
})

login

Log in to the RealWorld API If successful, the data result will be type {User}

Parameters

Examples

client.login(
  {
    email: 'mike@example.com',
    password: 'secret'
  },
  handleResponse
)

register

Register a new user with the RealWorld API

Parameters

Examples

client.register(
  {
    email: 'rick@example.com',
    password: 'shhhh',
    username: 'rick'
  },
  handleResponse
)

getUser

Get the logged in user

Parameters

Examples

client.getUser(handleResponse)

updateUser

Update the logged in user info

Parameters

  • opts Object
    • opts.email string email address of user (optional, default null)
    • opts.username string username of user (optional, default null)
    • opts.bio string biography of user (optional, default null)
    • opts.password string password of user (optional, default null)
    • opts.image string url of user image (optional, default null)
  • cb RealWorld~requestCallback Callback function

Examples

client.updateUser(
  {
    email: 'stacy@example.com',
    password: 'hush',
    username: 'stace',
    bio: 'riot grrl'
  },
  handleResponse
)

getProfile

Get profile of a user

Parameters

Examples

client.getProfile('rick', handleResponse)

followUser

Follow a user (authentication required)

Parameters

Examples

client.followUser('rick', handleResponse)

unFollowUser

Unfollow a user (authentication required)

Parameters

Examples

client.unFollowUser('rick', handleResponse)

listAllArticles

Request a list of 20 articles sorted by most recent in descending order

Parameters

Examples

client.listAllArticles(handleResponse)
client.listAllArticles(2, handleResponse)

listArticlesByTag

Request a list of 10 articles filtered by a tag and sorted by most recent in descending order

Parameters

Examples

client.listArticlesByTag('JavaScript', handleResponse)
client.listArticlesByTag('JavaScript', 2, handleResponse)

listArticlesByAuthor

Request a list of five articles filtered by author and sorted by most recent in descending order

Parameters

Examples

client.listArticlesByAuthor('rick', handleResponse)
client.listArticlesByAuthor('rick', 2, handleResponse)

listArticlesByAuthorFavorites

Request a list of 20 articles filtered by author favorites and sorted by most recent in descending order

Parameters

  • author string username of author to filter favorite articles by
  • page Number specify which page of articles to show (optional, default 0)
  • cb RealWorld~requestCallback Callback function

Examples

client.listArticlesByAuthorFavorites('rick', handleResponse)
client.listArticlesByAuthorFavorites('rick', 1, handleResponse)

feedArticles

Request a list of ten articles from the currently logged in users feed sorted by most recent in descending order (authentication required)

Parameters

Examples

client.feedArticles(handleResponse)
client.feedArticles(2, handleResponse)

getArticle

Request contents from a single article with the specified slug

Parameters

Examples

client.getArticle('angular-app-dev-e33mn9', handleResponse)

createArticle

Create a new article (authentication required)

Parameters

Examples

client.createArticle(
  {
    title: 'My awesome article',
    description: 'beep boop',
    body: 'wham bam thank you ma\'am',
    tagList: ['awesomeness', 'robots']
  },
  handleResponse
)

updateArticle

Update an existing article with given slug and options (authentication required)

Parameters

  • slug string shortname (slug) of article to update
  • opts Object
    • opts.title string title of article (optional, default null)
    • opts.description string short description of article (optional, default null)
    • opts.body string content of article (optional, default null)
  • cb RealWorld~requestCallback Callback function

Examples

client.updateArticle('my-awesome-article-ew9439', {
  title: 'my awesome gender neutral article',
  description: 'boop beep',
  body: 'wham bam thank you friend'
})

deleteArticle

Delete an existing article with the given slug (authentication required)

Parameters

Examples

client.deleteArticle('my-awesome-article-ew9439', handleResponse)

addComment

Add a comment to an article with the given slug (authentication required)

Parameters

Examples

client.addComment(
  'my-awesome-article-ew9439',
  {
    body: 'this is a good article'
  },
  handleResponse
)

getComments

Get comments from an article

Parameters

Examples

client.getComments('angular-app-dev-e33mn9', handleResponse)

deleteComment

Delete comment from an article (authentication required)

Parameters

Examples

client.deleteComment('angular-app-dev-e33mn9', 'e11dfeg', handleResponse)

favoriteArticle

Favorite an article (authentication required)

Parameters

Examples

client.favoriteArticle('my-awesome-article-ew9439', handleResponse)

unFavoriteArticle

Unfavorite an article (authentication required)

Parameters

Examples

client.unFavoriteArticle('my-awesome-article-ew9439', handleResponse)

getTags

Get a list of tags

Parameters

Examples

client.getTags(handleResponse)

setToken

Set the authentication token

Parameters

  • _token string authentication token to set

Examples

client.setToken('my-secret-authentication-token')

RealWorld~requestCallback

This callback is displayed as part of the RealWorld class. The error should be null if the method was able to run. HTTP and API errors are not caught as errors so that you can catch them yourself. For example, a response code 500 may return (null, { res.statusCode: 500, res.statusMessage: 'Internal Server Error' }, null).

API errors are returned with a 422 status code. Errors are included as JSON in the data result and are in the form of

{ "errors":{ "body": [ "can't be empty" ] } }

where body may be any parameter such as password, email, etc.

Successful API requests will return JSON data as seen in the RealWorld API Spec

Type: Function

Parameters

  • err Error error if method was unable to run
  • res Object response object from server
  • data Object data result from the server as JSON

Examples

function handleResponse (err, res, data) {
  if (err) return console.error(err)
  if (res.statusCode === 422 && data.errors) {
    Object.keys(data.errors).forEach(function (err) {
      var values = data.errors[err]
      values.forEach(function (v) {
        console.error(`${err} ${v}`)
      })
    })
    return
  }
  if (res.statusCode !== 200) {
    return console.log(`${res.statusCode}: ${res.statusMessage}`)
  }
  return console.log(data)
}

license

Copyright 2017 Nick Peihl

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

RealWorld library for open API calls using JavaScript

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published