realworld-api v1.0.2
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-apiusage
var RealWorld = require('realworld-api')
var client = new RealWorld()
client.getArticles(function (err, res, data) {
if (err) throw err
console.log(data)
})api
RealWorld
- See: RealWorld API Spec
Realworld library for open API calls using JavaScript
Parameters
optsObject? options for configuring 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
optsObjectcbRealWorld~requestCallback Callback function
Examples
client.login(
{
email: 'mike@example.com',
password: 'secret'
},
handleResponse
)register
Register a new user with the RealWorld API
Parameters
optsObjectcbRealWorld~requestCallback Callback function
Examples
client.register(
{
email: 'rick@example.com',
password: 'shhhh',
username: 'rick'
},
handleResponse
)getUser
Get the logged in user
Parameters
cbRealWorld~requestCallback Callback function
Examples
client.getUser(handleResponse)updateUser
Update the logged in user info
Parameters
optsObjectopts.emailstring email address of user (optional, defaultnull)opts.usernamestring username of user (optional, defaultnull)opts.biostring biography of user (optional, defaultnull)opts.passwordstring password of user (optional, defaultnull)opts.imagestring url of user image (optional, defaultnull)
cbRealWorld~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
usernamestring username of profile to retrievecbRealWorld~requestCallback Callback function
Examples
client.getProfile('rick', handleResponse)followUser
Follow a user (authentication required)
Parameters
usernamestring username to followcbRealWorld~requestCallback Callback function
Examples
client.followUser('rick', handleResponse)unFollowUser
Unfollow a user (authentication required)
Parameters
usernamestring username to unfollowcbRealWorld~requestCallback Callback function
Examples
client.unFollowUser('rick', handleResponse)listAllArticles
Request a list of 20 articles sorted by most recent in descending order
Parameters
pageNumber page specify which page of articles to show (optional, default0)cbRealWorld~requestCallback Callback function
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
tagstring tag name to filter bypageNumber specify which page of articles to show (optional, default0)cbRealWorld~requestCallback Callback function
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
authorstring username of author to filter bypageNumber specify which page of articles to show (optional, default0)cbRealWorld~requestCallback Callback function
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
authorstring username of author to filter favorite articles bypageNumber specify which page of articles to show (optional, default0)cbRealWorld~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
pageNumber specify which page of articles to show (optional, default0)cbRealWorld~requestCallback Callback function
Examples
client.feedArticles(handleResponse)client.feedArticles(2, handleResponse)getArticle
Request contents from a single article with the specified slug
Parameters
slugstring shortname (slug) of articlecbRealWorld~requestCallback Callback function
Examples
client.getArticle('angular-app-dev-e33mn9', handleResponse)createArticle
Create a new article (authentication required)
Parameters
optsObjectcbRealWorld~requestCallback Callback function
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
slugstring shortname (slug) of article to updateoptsObjectcbRealWorld~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
slugstring shortname (slug) of article to deletecbRealWorld~requestCallback Callback function
Examples
client.deleteArticle('my-awesome-article-ew9439', handleResponse)addComment
Add a comment to an article with the given slug (authentication required)
Parameters
slugstring shortname (slug) of article to add comment tooptsObjectopts.bodystring content of comment
cbRealWorld~requestCallback Callback function
Examples
client.addComment(
'my-awesome-article-ew9439',
{
body: 'this is a good article'
},
handleResponse
)getComments
Get comments from an article
Parameters
slugstring shortname (slug) of article from which to retrieve commentscbRealWorld~requestCallback Callback function
Examples
client.getComments('angular-app-dev-e33mn9', handleResponse)deleteComment
Delete comment from an article (authentication required)
Parameters
slugstring shortname (slug) of articlecommentIdstring unique id of comment to deletecbRealWorld~requestCallback Callback function
Examples
client.deleteComment('angular-app-dev-e33mn9', 'e11dfeg', handleResponse)favoriteArticle
Favorite an article (authentication required)
Parameters
slugstring shortname (slug) of article to favoritecbRealWorld~requestCallback Callback function
Examples
client.favoriteArticle('my-awesome-article-ew9439', handleResponse)unFavoriteArticle
Unfavorite an article (authentication required)
Parameters
slugstring shortname (slug) of article to unfavoritecbRealWorld~requestCallback Callback function
Examples
client.unFavoriteArticle('my-awesome-article-ew9439', handleResponse)getTags
Get a list of tags
Parameters
cbRealWorld~requestCallback Callback function
Examples
client.getTags(handleResponse)setToken
Set the authentication token
Parameters
_tokenstring 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
errError error if method was unable to runresObject response object from serverdataObject 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.