From e0ef8dd1c16a9e2d2ad9352ae94b428aa9712cb4 Mon Sep 17 00:00:00 2001 From: Miguel Laginha Date: Fri, 17 Apr 2020 17:21:19 +0100 Subject: [PATCH] refactor: even more enhancements and CC issues --- lib/api.activity.js | 13 +-- lib/api.admin.js | 39 ++++----- lib/api.authentication.js | 61 +++++++------ lib/api.config.js | 17 ++-- lib/api.content.js | 131 ++++++++++++++------------- lib/api.discussions.js | 60 +++++++------ lib/api.doc.js | 14 +-- lib/api.folders.js | 74 +++++++++------- lib/api.following.js | 19 ++-- lib/api.group.js | 100 +++++++++++---------- lib/api.invitations.js | 17 ++-- lib/api.lti.js | 19 ++-- lib/api.mediacore.js | 13 +-- lib/api.meetings-jitsi.js | 59 +++++++------ lib/api.meetups.js | 13 ++- lib/api.oauth.js | 21 +++-- lib/api.previews.js | 13 ++- lib/api.search.js | 27 +++--- lib/api.telemetry.js | 4 +- lib/api.tenants.js | 61 +++++++------ lib/api.ui.js | 30 ++++--- lib/api.user.js | 180 ++++++++++++++++++++------------------ lib/api.uservoice.js | 4 +- lib/api.version.js | 4 +- lib/model.js | 4 +- lib/util.js | 128 +++++++++++++++++---------- 26 files changed, 628 insertions(+), 497 deletions(-) diff --git a/lib/api.activity.js b/lib/api.activity.js index f71f4e0..fe0e704 100644 --- a/lib/api.activity.js +++ b/lib/api.activity.js @@ -15,6 +15,9 @@ import { performRestRequest, encodeURIComponent } from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Get the activity stream of the user in context. * @@ -28,7 +31,7 @@ import { performRestRequest, encodeURIComponent } from './util'; * @param {ActivityStream} callback.activityStream The stream of activities */ const getCurrentUserActivityStream = (restCtx, opts, callback) => { - performRestRequest(restCtx, '/api/activity', 'GET', opts, callback); + performRestRequest(restCtx, '/api/activity', HTTP_GET, opts, callback); }; /** @@ -45,7 +48,7 @@ const getCurrentUserActivityStream = (restCtx, opts, callback) => { * @param {ActivityStream} callback.activityStream The stream of activities */ const getActivityStream = (restCtx, activityStreamId, opts, callback) => { - performRestRequest(restCtx, '/api/activity/' + encodeURIComponent(activityStreamId), 'GET', opts, callback); + performRestRequest(restCtx, '/api/activity/' + encodeURIComponent(activityStreamId), HTTP_GET, opts, callback); }; /** @@ -61,7 +64,7 @@ const getActivityStream = (restCtx, activityStreamId, opts, callback) => { * @param {ActivityStream} callback.notificationStream The stream of notifications */ const getNotificationStream = (restCtx, opts, callback) => { - performRestRequest(restCtx, '/api/notifications', 'GET', opts, callback); + performRestRequest(restCtx, '/api/notifications', HTTP_GET, opts, callback); }; /** @@ -73,7 +76,7 @@ const getNotificationStream = (restCtx, opts, callback) => { * @param {Number} callback.lastReadTime The timestamp (millis since epoch) detailing the last time notifications were marked as read */ const markNotificationsRead = (restCtx, callback) => { - performRestRequest(restCtx, '/api/notifications/markRead', 'POST', null, callback); + performRestRequest(restCtx, '/api/notifications/markRead', HTTP_POST, null, callback); }; /** @@ -84,7 +87,7 @@ const markNotificationsRead = (restCtx, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const collect = (restCtx, callback) => { - performRestRequest(restCtx, '/api/activity/collect', 'POST', null, callback); + performRestRequest(restCtx, '/api/activity/collect', HTTP_POST, null, callback); }; export { collect, markNotificationsRead, getNotificationStream, getActivityStream, getCurrentUserActivityStream }; diff --git a/lib/api.admin.js b/lib/api.admin.js index e52c860..d090da9 100644 --- a/lib/api.admin.js +++ b/lib/api.admin.js @@ -14,10 +14,17 @@ */ import util from 'util'; +import { defaultTo, compose, not, equals } from 'ramda'; import { RestContext } from './model'; import { performRestRequest, encodeURIComponent } from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + +// Auxiliary functions +const isNot302 = compose(not, equals(302)); + // This file aggregates those REST calls that are only beneficial to a global and/or tenant administrators. // It's expected that the RestContext objects that are passed into these methods reflect authenticated users whom are all administrators @@ -31,7 +38,7 @@ import { performRestRequest, encodeURIComponent } from './util'; * @param {Object} callback.requestInfo The request info object containing the `url` and signed POST `body` to use to authenticate to the specified tenant */ const getSignedTenantAuthenticationRequestInfo = (globalAdminRestCtx, tenantAlias, callback) => { - performRestRequest(globalAdminRestCtx, '/api/auth/signed/tenant', 'GET', { tenant: tenantAlias }, callback); + performRestRequest(globalAdminRestCtx, '/api/auth/signed/tenant', HTTP_GET, { tenant: tenantAlias }, callback); }; /** @@ -44,7 +51,7 @@ const getSignedTenantAuthenticationRequestInfo = (globalAdminRestCtx, tenantAlia * @param {Object} callback.requestInfo The request info object containing the `url` and signed POST `body` to use to authenticate and become the specified user */ const getSignedBecomeUserAuthenticationRequestInfo = (adminRestCtx, becomeUserId, callback) => { - performRestRequest(adminRestCtx, '/api/auth/signed/become', 'GET', { becomeUserId }, callback); + performRestRequest(adminRestCtx, '/api/auth/signed/become', HTTP_GET, { becomeUserId }, callback); }; /** @@ -60,12 +67,10 @@ const getSignedBecomeUserAuthenticationRequestInfo = (adminRestCtx, becomeUserId * @param {Object} callback.err An error that occurred, if any */ const doSignedAuthentication = (restCtx, body, callback) => { - performRestRequest(restCtx, '/api/auth/signed', 'POST', body, (err, body, response) => { - if (err) { - return callback(err); - } + performRestRequest(restCtx, '/api/auth/signed', HTTP_POST, body, (err, body, response) => { + if (err) return callback(err); - if (response.statusCode !== 302) { + if (isNot302(response.statusCode)) { return callback({ code: response.statusCode, msg: 'Unexpected response code' @@ -92,15 +97,13 @@ const doSignedAuthentication = (restCtx, body, callback) => { const _doSignedAuthenticationWithRequestInfo = (requestInfo, internalBaseUrl, strictSSL, callback) => { const parsedUrl = new URL(requestInfo.url); - const baseUrl = internalBaseUrl || util.format('%s//%s', parsedUrl.protocol, parsedUrl.host); + const baseUrl = defaultTo(util.format('%s//%s', parsedUrl.protocol, parsedUrl.host), internalBaseUrl); const authenticatingRestCtx = new RestContext(baseUrl, { hostHeader: parsedUrl.host, strictSSL }); doSignedAuthentication(authenticatingRestCtx, requestInfo.body, err => { - if (err) { - return callback(err); - } + if (err) return callback(err); return callback(null, authenticatingRestCtx); }); @@ -118,9 +121,7 @@ const _doSignedAuthenticationWithRequestInfo = (requestInfo, internalBaseUrl, st */ const loginAsUser = (adminRestCtx, becomeUserId, targetInternalBaseUrl, callback) => { getSignedBecomeUserAuthenticationRequestInfo(adminRestCtx, becomeUserId, (err, requestInfo) => { - if (err) { - return callback(err); - } + if (err) return callback(err); return _doSignedAuthenticationWithRequestInfo(requestInfo, targetInternalBaseUrl, adminRestCtx.strictSSL, callback); }); @@ -138,9 +139,7 @@ const loginAsUser = (adminRestCtx, becomeUserId, targetInternalBaseUrl, callback */ const loginOnTenant = (globalAdminRestCtx, tenantAlias, targetInternalBaseUrl, callback) => { getSignedTenantAuthenticationRequestInfo(globalAdminRestCtx, tenantAlias, (err, requestInfo) => { - if (err) { - return callback(err); - } + if (err) return callback(err); return _doSignedAuthenticationWithRequestInfo( requestInfo, @@ -178,7 +177,7 @@ const importUsers = (restCtx, tenantAlias, csvGenerator, authenticationStrategy, forceProfileUpdate, file: csvGenerator }; - performRestRequest(restCtx, '/api/user/import', 'POST', params, callback); + performRestRequest(restCtx, '/api/user/import', HTTP_POST, params, callback); }; /** @@ -191,8 +190,8 @@ const importUsers = (restCtx, tenantAlias, csvGenerator, authenticationStrategy, * @param {User[]} callback.response The users for the given tenantAlias */ const getAllUsersForTenant = (adminRestCtx, tenantAlias, callback) => { - const url = '/api/tenants/' + encodeURIComponent(tenantAlias) + '/users'; - performRestRequest(adminRestCtx, url, 'GET', {}, callback); + const url = `/api/tenants/${encodeURIComponent(tenantAlias)}/users`; + performRestRequest(adminRestCtx, url, HTTP_GET, {}, callback); }; export { diff --git a/lib/api.authentication.js b/lib/api.authentication.js index 35ba2f7..6fdbbc1 100644 --- a/lib/api.authentication.js +++ b/lib/api.authentication.js @@ -15,6 +15,9 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Log a user in through the REST API * @@ -25,7 +28,7 @@ import * as RestUtil from './util'; * @param {Object} callback.err Error object containing error code and error message */ const login = (restCtx, username, password, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/login', 'POST', { username, password }, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/login', HTTP_POST, { username, password }, callback); }; /** @@ -36,7 +39,7 @@ const login = (restCtx, username, password, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const logout = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/logout', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/logout', HTTP_POST, null, callback); }; /** @@ -57,8 +60,8 @@ const changePassword = (restCtx, userId, oldPassword, newPassword, callback) => RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/password', - 'POST', + `/api/user/${RestUtil.encodeURIComponent(userId)}/password`, + HTTP_POST, params, callback ); @@ -75,8 +78,8 @@ const changePassword = (restCtx, userId, oldPassword, newPassword, callback) => const exists = (restCtx, username, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/exists/' + RestUtil.encodeURIComponent(username), - 'GET', + `/api/auth/exists/${RestUtil.encodeURIComponent(username)}`, + HTTP_GET, null, callback ); @@ -94,8 +97,8 @@ const exists = (restCtx, username, callback) => { const existsOnTenant = (restCtx, tenantAlias, username, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/' + RestUtil.encodeURIComponent(tenantAlias) + '/exists/' + RestUtil.encodeURIComponent(username), - 'GET', + `/api/auth/${RestUtil.encodeURIComponent(tenantAlias)}/exists/${RestUtil.encodeURIComponent(username)}`, + HTTP_GET, null, callback ); @@ -113,16 +116,16 @@ const existsOnTenant = (restCtx, tenantAlias, username, callback) => { const getUserLoginIds = (restCtx, userId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/loginIds/' + RestUtil.encodeURIComponent(userId), - 'GET', + `/api/auth/loginIds/${RestUtil.encodeURIComponent(userId)}`, + HTTP_GET, null, callback ); }; -/// ///////////////////////////////////// -// External authentication strategies // -/// ///////////////////////////////////// +/** + * External authentication strategies + */ /** * Initiate the three-legged OAuth authorization steps for Twitter authentication @@ -134,7 +137,7 @@ const getUserLoginIds = (restCtx, userId, callback) => { * @param {Object} callback.response The HTTP response object */ const twitterRedirect = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/twitter', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/twitter', HTTP_POST, null, callback); }; /** @@ -148,7 +151,7 @@ const twitterRedirect = (restCtx, callback) => { * @param {Object} callback.response The HTTP response object */ const twitterCallback = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/twitter/callback', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/twitter/callback', HTTP_GET, params, callback); }; /** @@ -161,7 +164,7 @@ const twitterCallback = (restCtx, params, callback) => { * @param {Object} callback.response The HTTP response object */ const facebookRedirect = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/facebook', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/facebook', HTTP_POST, null, callback); }; /** @@ -175,7 +178,7 @@ const facebookRedirect = (restCtx, callback) => { * @param {Object} callback.response The HTTP response object */ const facebookCallback = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/facebook/callback', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/facebook/callback', HTTP_GET, params, callback); }; /** @@ -188,7 +191,7 @@ const facebookCallback = (restCtx, params, callback) => { * @param {Object} callback.response The HTTP response object */ const googleRedirect = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/google', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/google', HTTP_POST, null, callback); }; /** @@ -202,7 +205,7 @@ const googleRedirect = (restCtx, callback) => { * @param {Object} callback.response The HTTP response object */ const googleCallback = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/google/callback', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/google/callback', HTTP_GET, params, callback); }; /** @@ -215,7 +218,7 @@ const googleCallback = (restCtx, params, callback) => { * @param {Object} callback.response The HTTP response object */ const casRedirect = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/cas', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/cas', HTTP_POST, null, callback); }; /** @@ -229,7 +232,7 @@ const casRedirect = (restCtx, callback) => { * @param {Object} callback.response The HTTP response object */ const casCallback = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/cas/callback', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/cas/callback', HTTP_GET, params, callback); }; /** @@ -243,7 +246,7 @@ const casCallback = (restCtx, params, callback) => { * @param {Object} callback.response The HTTP response object */ const shibbolethTenantRedirect = (restCtx, redirectUrl, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth', 'POST', { redirectUrl }, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth', HTTP_POST, { redirectUrl }, callback); }; /** @@ -260,7 +263,7 @@ const shibbolethTenantRedirect = (restCtx, redirectUrl, callback) => { * @param {Object} callback.response The HTTP response object */ const shibbolethSPRedirect = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/sp', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/sp', HTTP_GET, params, callback); }; /** @@ -275,7 +278,7 @@ const shibbolethSPRedirect = (restCtx, params, callback) => { */ const shibbolethSPCallback = (restCtx, attributes, callback) => { restCtx.additionalHeaders = attributes; - RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/sp/callback', 'GET', null, function(...args) { + RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/sp/callback', HTTP_GET, null, function(...args) { delete restCtx.additionalHeaders; return callback.apply(this, args); }); @@ -295,7 +298,7 @@ const shibbolethSPCallback = (restCtx, attributes, callback) => { * @param {Object} callback.response The HTTP response object */ const shibbolethTenantCallback = (restCtx, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/callback', 'GET', params, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/shibboleth/callback', HTTP_GET, params, callback); }; /** @@ -308,7 +311,7 @@ const shibbolethTenantCallback = (restCtx, params, callback) => { * @param {Object} callback.err An error that occurred, if any */ const ldapLogin = (restCtx, username, password, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/ldap', 'POST', { username, password }, callback); + RestUtil.performRestRequest(restCtx, '/api/auth/ldap', HTTP_POST, { username, password }, callback); }; /** @@ -320,7 +323,7 @@ const ldapLogin = (restCtx, username, password, callback) => { * @param {Object} callback.err An error that occurred, if any */ const getResetPasswordSecret = (restCtx, username, callback) => { - RestUtil.performRestRequest(restCtx, '/api/auth/local/reset/secret/' + username, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/auth/local/reset/secret/${username}`, HTTP_GET, null, callback); }; /** @@ -336,8 +339,8 @@ const getResetPasswordSecret = (restCtx, username, callback) => { const resetPassword = (restCtx, username, secret, newPassword, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/local/reset/password/' + username, - 'POST', + `/api/auth/local/reset/password/${username}`, + HTTP_POST, { secret, newPassword }, callback ); diff --git a/lib/api.config.js b/lib/api.config.js index 3c2c6d4..3c8f90f 100644 --- a/lib/api.config.js +++ b/lib/api.config.js @@ -15,6 +15,9 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Get the global config schema through the REST API. This should only return for a global or tenant admin. * @@ -24,7 +27,7 @@ import * as RestUtil from './util'; * @param {Object} callback.schema JSON object representing the global config schema */ const getSchema = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/config/schema', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/config/schema', HTTP_GET, null, callback); }; /** @@ -39,10 +42,10 @@ const getSchema = (restCtx, callback) => { const getTenantConfig = (restCtx, tenantAlias, callback) => { let url = '/api/config'; if (tenantAlias) { - url += '/' + RestUtil.encodeURIComponent(tenantAlias); + url += `/${RestUtil.encodeURIComponent(tenantAlias)}`; } - RestUtil.performRestRequest(restCtx, url, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, null, callback); }; /** @@ -57,10 +60,10 @@ const getTenantConfig = (restCtx, tenantAlias, callback) => { const updateConfig = (restCtx, tenantAlias, update, callback) => { let url = '/api/config'; if (tenantAlias) { - url += '/' + RestUtil.encodeURIComponent(tenantAlias); + url += `/${RestUtil.encodeURIComponent(tenantAlias)}`; } - RestUtil.performRestRequest(restCtx, url, 'POST', update, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, update, callback); }; /** @@ -75,11 +78,11 @@ const updateConfig = (restCtx, tenantAlias, update, callback) => { const clearConfig = (restCtx, tenantAlias, configFields, callback) => { let url = '/api/config'; if (tenantAlias) { - url += '/' + RestUtil.encodeURIComponent(tenantAlias); + url += `/${RestUtil.encodeURIComponent(tenantAlias)}`; } url += '/clear'; - RestUtil.performRestRequest(restCtx, url, 'POST', { configFields }, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, { configFields }, callback); }; export { getSchema, getTenantConfig, clearConfig, updateConfig }; diff --git a/lib/api.content.js b/lib/api.content.js index 5616c8c..293b6cc 100644 --- a/lib/api.content.js +++ b/lib/api.content.js @@ -14,11 +14,15 @@ */ import fs from 'fs'; -import _ from 'underscore'; import request from 'request'; +import { is, compose, defaultTo, includes, and, not } from 'ramda'; import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_DELETE = 'DELETE'; + /** * Get a full content profile through the REST API. * @@ -29,7 +33,13 @@ import * as RestUtil from './util'; * @param {Content} callback.content Content object representing the retrieved content */ const getContent = (restCtx, contentId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/content/' + RestUtil.encodeURIComponent(contentId), 'GET', null, callback); + RestUtil.performRestRequest( + restCtx, + `/api/content/${RestUtil.encodeURIComponent(contentId)}`, + HTTP_GET, + null, + callback + ); }; /** @@ -59,7 +69,7 @@ const createLink = (restCtx, linkDetails, callback) => { viewers, folders }; - RestUtil.performRestRequest(restCtx, '/api/content/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, '/api/content/create', HTTP_POST, params, callback); }; /** @@ -89,7 +99,7 @@ const createFile = (restCtx, fileDetails, callback) => { viewers, folders }; - RestUtil.performRestRequest(restCtx, '/api/content/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, '/api/content/create', HTTP_POST, params, callback); }; /** @@ -128,7 +138,7 @@ const createCollabDoc = ( viewers, folders }; - RestUtil.performRestRequest(restCtx, '/api/content/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, '/api/content/create', HTTP_POST, params, callback); }; /** @@ -146,7 +156,7 @@ const createCollabDoc = ( * @param {Object} callback.err Error object containing error code and error message * @param {Content} callback.content Content object representing the created content */ -const createCollabsheet = function( +const createCollabsheet = ( restCtx, displayName, description, @@ -156,7 +166,7 @@ const createCollabsheet = function( viewers, folders, callback -) { +) => { const params = { resourceSubType: 'collabsheet', displayName, @@ -167,7 +177,7 @@ const createCollabsheet = function( viewers, folders }; - RestUtil.performRestRequest(restCtx, '/api/content/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, '/api/content/create', HTTP_POST, params, callback); }; /** @@ -183,8 +193,8 @@ const createCollabsheet = function( const updateContent = (restCtx, contentId, params, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId), - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}`, + HTTP_POST, params, callback ); @@ -201,8 +211,8 @@ const updateContent = (restCtx, contentId, params, callback) => { const deleteContent = (restCtx, contentId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId), - 'DELETE', + `/api/content/${RestUtil.encodeURIComponent(contentId)}`, + HTTP_DELETE, null, callback ); @@ -226,8 +236,8 @@ const getMembers = (restCtx, contentId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/members', - 'GET', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/members`, + HTTP_GET, params, callback ); @@ -245,8 +255,8 @@ const getMembers = (restCtx, contentId, start, limit, callback) => { const updateMembers = (restCtx, contentId, updatedMembers, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/members', - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/members`, + HTTP_POST, updatedMembers, callback ); @@ -264,8 +274,8 @@ const updateMembers = (restCtx, contentId, updatedMembers, callback) => { const shareContent = (restCtx, contentId, principals, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/share', - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/share`, + HTTP_POST, { viewers: principals }, callback ); @@ -285,8 +295,8 @@ const shareContent = (restCtx, contentId, principals, callback) => { const createComment = (restCtx, contentId, body, replyTo, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/messages', - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/messages`, + HTTP_POST, { body, replyTo }, callback ); @@ -305,8 +315,8 @@ const createComment = (restCtx, contentId, body, replyTo, callback) => { const deleteComment = (restCtx, contentId, created, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/messages/' + RestUtil.encodeURIComponent(created), - 'DELETE', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/messages/${RestUtil.encodeURIComponent(created)}`, + HTTP_DELETE, null, callback ); @@ -330,8 +340,8 @@ const getComments = (restCtx, contentId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/messages', - 'GET', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/messages`, + HTTP_GET, params, callback ); @@ -355,8 +365,8 @@ const getLibrary = (restCtx, principalId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/content/library/' + RestUtil.encodeURIComponent(principalId), - 'GET', + `/api/content/library/${RestUtil.encodeURIComponent(principalId)}`, + HTTP_GET, params, callback ); @@ -372,9 +382,10 @@ const getLibrary = (restCtx, principalId, start, limit, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const removeContentFromLibrary = (restCtx, principalId, contentId, callback) => { - const url = - '/api/content/library/' + RestUtil.encodeURIComponent(principalId) + '/' + RestUtil.encodeURIComponent(contentId); - RestUtil.performRestRequest(restCtx, url, 'DELETE', null, callback); + const url = `/api/content/library/${RestUtil.encodeURIComponent(principalId)}/${RestUtil.encodeURIComponent( + contentId + )}`; + RestUtil.performRestRequest(restCtx, url, HTTP_DELETE, null, callback); }; /** @@ -395,8 +406,8 @@ const getRevisions = (restCtx, contentId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/revisions', - 'GET', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/revisions`, + HTTP_GET, params, callback ); @@ -413,9 +424,10 @@ const getRevisions = (restCtx, contentId, start, limit, callback) => { * @param {Revision} callback.revision Revision object representing the retrieved revision. */ const getRevision = (restCtx, contentId, revisionId, callback) => { - const url = - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/revisions/' + RestUtil.encodeURIComponent(revisionId); - RestUtil.performRestRequest(restCtx, url, 'GET', null, callback); + const url = `/api/content/${RestUtil.encodeURIComponent(contentId)}/revisions/${RestUtil.encodeURIComponent( + revisionId + )}`; + RestUtil.performRestRequest(restCtx, url, HTTP_GET, null, callback); }; /** @@ -428,13 +440,10 @@ const getRevision = (restCtx, contentId, revisionId, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const restoreRevision = (restCtx, contentId, revisionId, callback) => { - const url = - '/api/content/' + - RestUtil.encodeURIComponent(contentId) + - '/revisions/' + - RestUtil.encodeURIComponent(revisionId) + - '/restore'; - RestUtil.performRestRequest(restCtx, url, 'POST', null, callback); + const url = `/api/content/${RestUtil.encodeURIComponent(contentId)}/revisions/${RestUtil.encodeURIComponent( + revisionId + )}/restore`; + RestUtil.performRestRequest(restCtx, url, HTTP_POST, null, callback); }; /** @@ -453,8 +462,8 @@ const updateFileBody = (restCtx, contentId, file, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/newversion', - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/newversion`, + HTTP_POST, params, callback ); @@ -476,15 +485,15 @@ const download = (restCtx, contentId, revisionId, path, callback) => { * Performs the correct HTTP request to download a file. * This function assumes a proper cookiejar can be found on the RestContext objext. */ - const downloadFile = function() { - let url = restCtx.host + '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/download'; + const downloadFile = () => { + let url = `${restCtx.host}/api/content/${RestUtil.encodeURIComponent(contentId)}/download`; if (revisionId) { - url += '/' + revisionId; + url += `/${revisionId}`; } const requestParams = { url, - method: 'GET', + method: HTTP_GET, jar: restCtx.cookieJar, strictSSL: restCtx.strictSSL }; @@ -502,7 +511,7 @@ const download = (restCtx, contentId, revisionId, path, callback) => { // Destroy the stream and notify the caller. writeStream.removeAllListeners(); writeStream.destroy(); - if (!called) { + if (not(called)) { called = true; callback(null, response); } @@ -514,7 +523,7 @@ const download = (restCtx, contentId, revisionId, path, callback) => { writeStream.removeAllListeners(); writeStream.destroy(); - if (!called) { + if (not(called)) { called = true; callback(err, response); } @@ -535,7 +544,8 @@ const download = (restCtx, contentId, revisionId, path, callback) => { req.on('end', () => { // If we get anything besides a 200 or 204, it's an error. - if (![200, 204].includes(response.statusCode) && !called) { + const aint200or204 = code => compose(not, includes)(code, [200, 204]); + if (and(aint200or204(response.statusCode), not(called))) { called = true; callback({ code: response.statusCode, @@ -557,9 +567,7 @@ const download = (restCtx, contentId, revisionId, path, callback) => { // If the restContext is not anonymous, we need to fill it up. RestUtil.fillCookieJar(restCtx, err => { - if (err) { - return callback(err); - } + if (err) return callback(err); downloadFile(); }); @@ -578,8 +586,8 @@ const download = (restCtx, contentId, revisionId, path, callback) => { const joinCollabDoc = (restCtx, contentId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/content/' + RestUtil.encodeURIComponent(contentId) + '/join', - 'POST', + `/api/content/${RestUtil.encodeURIComponent(contentId)}/join`, + HTTP_POST, null, callback ); @@ -612,8 +620,9 @@ const setPreviewItems = ( previewMetadata, callback ) => { - previewMetadata = previewMetadata || {}; - contentMetadata = contentMetadata || {}; + previewMetadata = defaultTo({}, previewMetadata); + contentMetadata = defaultTo({}, contentMetadata); + const params = { status, sizes: {}, @@ -624,7 +633,7 @@ const setPreviewItems = ( // Add the files and their sizes to the parameters. Object.keys(files).forEach(filename => { - if (_.isString(files[filename])) { + if (is(String, files[filename])) { params.links[filename] = files[filename]; } else { params[filename] = files[filename]; @@ -640,7 +649,7 @@ const setPreviewItems = ( '/revisions/' + RestUtil.encodeURIComponent(revisionId) + '/previews'; - RestUtil.performRestRequest(restCtx, url, 'POST', params, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, callback); }; /** @@ -659,7 +668,7 @@ const getPreviewItems = (restCtx, contentId, revisionId, callback) => { '/revisions/' + RestUtil.encodeURIComponent(revisionId) + '/previews'; - RestUtil.performRestRequest(restCtx, url, 'GET', {}, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, {}, callback); }; /** @@ -690,7 +699,7 @@ const downloadPreviewItem = (restCtx, contentId, revisionId, previewItem, signat expires: signature.expires, lastmodified: signature.lastModified }; - RestUtil.performRestRequest(restCtx, url, 'GET', params, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, params, callback); }; export { diff --git a/lib/api.discussions.js b/lib/api.discussions.js index 7147eb7..6297afa 100644 --- a/lib/api.discussions.js +++ b/lib/api.discussions.js @@ -15,6 +15,10 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_DELETE = 'DELETE'; + /** * Create a new discussion. * @@ -36,7 +40,7 @@ const createDiscussion = (restCtx, displayName, description, visibility, manager managers, members }; - RestUtil.performRestRequest(restCtx, '/api/discussion/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, `/api/discussion/create`, HTTP_POST, params, callback); }; /** @@ -56,8 +60,8 @@ const createDiscussion = (restCtx, displayName, description, visibility, manager const getDiscussion = (restCtx, discussionId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId), - 'GET', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}`, + HTTP_GET, null, callback ); @@ -76,8 +80,8 @@ const getDiscussion = (restCtx, discussionId, callback) => { const updateDiscussion = (restCtx, discussionId, profileFields, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId), - 'POST', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}`, + HTTP_POST, profileFields, callback ); @@ -94,8 +98,8 @@ const updateDiscussion = (restCtx, discussionId, profileFields, callback) => { const deleteDiscussion = (restCtx, discussionId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId), - 'DELETE', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}`, + HTTP_DELETE, null, callback ); @@ -121,8 +125,8 @@ const getDiscussionsLibrary = (restCtx, principalId, start, limit, callback) => }; RestUtil.performRestRequest( restCtx, - '/api/discussion/library/' + RestUtil.encodeURIComponent(principalId), - 'GET', + `/api/discussion/library/${RestUtil.encodeURIComponent(principalId)}`, + HTTP_GET, params, callback ); @@ -148,8 +152,8 @@ const getDiscussionMembers = (restCtx, discussionId, start, limit, callback) => }; RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId) + '/members', - 'GET', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/members`, + HTTP_GET, params, callback ); @@ -168,8 +172,8 @@ const getDiscussionMembers = (restCtx, discussionId, start, limit, callback) => const updateDiscussionMembers = (restCtx, discussionId, memberUpdates, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId) + '/members', - 'POST', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/members`, + HTTP_POST, memberUpdates, callback ); @@ -192,8 +196,8 @@ const shareDiscussion = (restCtx, discussionId, principalIds, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId) + '/share', - 'POST', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/share`, + HTTP_POST, params, callback ); @@ -214,11 +218,10 @@ const shareDiscussion = (restCtx, discussionId, principalIds, callback) => { const removeDiscussionFromLibrary = (restCtx, libraryOwnerId, discussionId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/library/' + - RestUtil.encodeURIComponent(libraryOwnerId) + - '/' + - RestUtil.encodeURIComponent(discussionId), - 'DELETE', + `/api/discussion/library/${RestUtil.encodeURIComponent(libraryOwnerId)}/${RestUtil.encodeURIComponent( + discussionId + )}`, + HTTP_DELETE, null, callback ); @@ -243,8 +246,8 @@ const createMessage = (restCtx, discussionId, body, replyTo, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId) + '/messages', - 'POST', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/messages`, + HTTP_POST, params, callback ); @@ -269,8 +272,8 @@ const getMessages = (restCtx, discussionId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/discussion/' + RestUtil.encodeURIComponent(discussionId) + '/messages', - 'GET', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/messages`, + HTTP_GET, params, callback ); @@ -290,11 +293,10 @@ const getMessages = (restCtx, discussionId, start, limit, callback) => { const deleteMessage = (restCtx, discussionId, messageCreated, callback) => { RestUtil.performRestRequest( restCtx, - '/api/discussion/' + - RestUtil.encodeURIComponent(discussionId) + - '/messages/' + - RestUtil.encodeURIComponent(messageCreated), - 'DELETE', + `/api/discussion/${RestUtil.encodeURIComponent(discussionId)}/messages/${RestUtil.encodeURIComponent( + messageCreated + )}`, + HTTP_DELETE, null, callback ); diff --git a/lib/api.doc.js b/lib/api.doc.js index 25d3e4a..4fd5193 100644 --- a/lib/api.doc.js +++ b/lib/api.doc.js @@ -15,6 +15,10 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_DELETE = 'DELETE'; + /** * Get a list of all of the available modules of a certain type through the REST API. * @@ -25,7 +29,7 @@ import * as RestUtil from './util'; * @param {String[]} callback.modules Array containing the names of all of the available modules */ const getModules = (restCtx, type, callback) => { - RestUtil.performRestRequest(restCtx, '/api/doc/' + RestUtil.encodeURIComponent(type), 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/doc/${RestUtil.encodeURIComponent(type)}`, HTTP_GET, null, callback); }; /** @@ -41,8 +45,8 @@ const getModules = (restCtx, type, callback) => { const getModuleDocumentation = (restCtx, type, moduleId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/doc/' + RestUtil.encodeURIComponent(type) + '/' + RestUtil.encodeURIComponent(moduleId), - 'GET', + `/api/doc/${RestUtil.encodeURIComponent(type)}/${RestUtil.encodeURIComponent(moduleId)}`, + HTTP_GET, null, callback ); @@ -57,7 +61,7 @@ const getModuleDocumentation = (restCtx, type, moduleId, callback) => { * @param {Object} callback.info The swagger root information */ const getSwaggerResources = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/swagger', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/swagger`, HTTP_GET, null, callback); }; /** @@ -69,7 +73,7 @@ const getSwaggerResources = (restCtx, callback) => { * @param {Object} callback.info The swagger information for the given api */ const getSwaggerApi = (restCtx, id, callback) => { - RestUtil.performRestRequest(restCtx, '/api/swagger/' + id, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/swagger/${id}`, HTTP_GET, null, callback); }; export { getModules, getModuleDocumentation, getSwaggerResources, getSwaggerApi }; diff --git a/lib/api.folders.js b/lib/api.folders.js index 5c62049..1365043 100644 --- a/lib/api.folders.js +++ b/lib/api.folders.js @@ -15,6 +15,10 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_DELETE = 'DELETE'; + /** * Get a folder by its id * @@ -25,7 +29,13 @@ import * as RestUtil from './util'; * @param {Folder} callback.folder The retrieved folder */ const getFolder = (restCtx, folderId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/folder/' + RestUtil.encodeURIComponent(folderId), 'GET', null, callback); + RestUtil.performRestRequest( + restCtx, + `/api/folder/${RestUtil.encodeURIComponent(folderId)}`, + HTTP_GET, + null, + callback + ); }; /** @@ -49,7 +59,7 @@ const createFolder = (restCtx, displayName, description, visibility, managers, v managers, viewers }; - RestUtil.performRestRequest(restCtx, '/api/folder', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, `/api/folder`, HTTP_POST, params, callback); }; /** @@ -68,8 +78,8 @@ const createFolder = (restCtx, displayName, description, visibility, managers, v const updateFolder = (restCtx, folderId, updates, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId), - 'POST', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}`, + HTTP_POST, updates, callback ); @@ -86,8 +96,8 @@ const updateFolder = (restCtx, folderId, updates, callback) => { */ const updateFolderContentVisibility = (restCtx, folderId, visibility, callback) => { const params = { visibility }; - const url = '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/contentvisibility'; - RestUtil.performRestRequest(restCtx, url, 'POST', params, callback); + const url = `/api/folder/${RestUtil.encodeURIComponent(folderId)}/contentvisibility`; + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, callback); }; /** @@ -105,8 +115,8 @@ const deleteFolder = (restCtx, folderId, deleteContent, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId), - 'DELETE', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}`, + HTTP_DELETE, params, callback ); @@ -124,8 +134,8 @@ const deleteFolder = (restCtx, folderId, deleteContent, callback) => { const shareFolder = (restCtx, folderId, principalIds, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/share', - 'POST', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/share`, + HTTP_POST, { viewers: principalIds }, callback ); @@ -143,8 +153,8 @@ const shareFolder = (restCtx, folderId, principalIds, callback) => { const updateFolderMembers = (restCtx, folderId, memberUpdates, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/members', - 'POST', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/members`, + HTTP_POST, memberUpdates, callback ); @@ -170,8 +180,8 @@ const getFolderMembers = (restCtx, folderId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/members', - 'GET', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/members`, + HTTP_GET, params, callback ); @@ -197,8 +207,8 @@ const getFoldersLibrary = (restCtx, principalId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/library/' + RestUtil.encodeURIComponent(principalId), - 'GET', + `/api/folder/library/${RestUtil.encodeURIComponent(principalId)}`, + HTTP_GET, params, callback ); @@ -213,7 +223,7 @@ const getFoldersLibrary = (restCtx, principalId, start, limit, callback) => { * @param {Folder[]} callback.folders The folders the current user manages */ const getManagedFolders = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/folder/managed', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/folder/managed', HTTP_GET, null, callback); }; /** @@ -228,9 +238,9 @@ const getManagedFolders = (restCtx, callback) => { */ const removeFolderFromLibrary = (restCtx, principalId, folderId, callback) => { let url = '/api/folder/library'; - url += '/' + RestUtil.encodeURIComponent(principalId); - url += '/' + RestUtil.encodeURIComponent(folderId); - RestUtil.performRestRequest(restCtx, url, 'DELETE', null, callback); + url += `/${RestUtil.encodeURIComponent(principalId)}`; + url += `/${RestUtil.encodeURIComponent(folderId)}`; + RestUtil.performRestRequest(restCtx, url, HTTP_DELETE, null, callback); }; /** @@ -245,8 +255,8 @@ const removeFolderFromLibrary = (restCtx, principalId, folderId, callback) => { const addContentItemsToFolder = (restCtx, folderId, contentIds, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/library', - 'POST', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/library`, + HTTP_POST, { contentIds }, callback ); @@ -264,8 +274,8 @@ const addContentItemsToFolder = (restCtx, folderId, contentIds, callback) => { const removeContentItemsFromFolder = (restCtx, folderId, contentIds, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/library', - 'DELETE', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/library`, + HTTP_DELETE, { contentIds }, callback ); @@ -291,8 +301,8 @@ const getFolderContentLibrary = (restCtx, folderId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/library', - 'GET', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/library`, + HTTP_GET, params, callback ); @@ -317,8 +327,8 @@ const createMessage = (restCtx, folderId, body, replyTo, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/messages', - 'POST', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/messages`, + HTTP_POST, params, callback ); @@ -343,8 +353,8 @@ const getMessages = (restCtx, folderId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/messages', - 'GET', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/messages`, + HTTP_GET, params, callback ); @@ -364,8 +374,8 @@ const getMessages = (restCtx, folderId, start, limit, callback) => { const deleteMessage = (restCtx, folderId, messageCreated, callback) => { RestUtil.performRestRequest( restCtx, - '/api/folder/' + RestUtil.encodeURIComponent(folderId) + '/messages/' + RestUtil.encodeURIComponent(messageCreated), - 'DELETE', + `/api/folder/${RestUtil.encodeURIComponent(folderId)}/messages/${RestUtil.encodeURIComponent(messageCreated)}`, + HTTP_DELETE, null, callback ); diff --git a/lib/api.following.js b/lib/api.following.js index 080aa5b..ec6edbf 100644 --- a/lib/api.following.js +++ b/lib/api.following.js @@ -15,6 +15,9 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Get the list of followers of a user * @@ -31,8 +34,8 @@ import * as RestUtil from './util'; const getFollowers = (restCtx, userId, start, limit, callback) => { RestUtil.performRestRequest( restCtx, - '/api/following/' + RestUtil.encodeURIComponent(userId) + '/followers', - 'GET', + `/api/following/${RestUtil.encodeURIComponent(userId)}/followers`, + HTTP_GET, { start, limit }, callback ); @@ -54,8 +57,8 @@ const getFollowers = (restCtx, userId, start, limit, callback) => { const getFollowing = (restCtx, userId, start, limit, callback) => { RestUtil.performRestRequest( restCtx, - '/api/following/' + RestUtil.encodeURIComponent(userId) + '/following', - 'GET', + `/api/following/${RestUtil.encodeURIComponent(userId)}/following`, + HTTP_GET, { start, limit }, callback ); @@ -72,8 +75,8 @@ const getFollowing = (restCtx, userId, start, limit, callback) => { const follow = (restCtx, userId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/following/' + RestUtil.encodeURIComponent(userId) + '/follow', - 'POST', + `/api/following/${RestUtil.encodeURIComponent(userId)}/follow`, + HTTP_POST, null, callback ); @@ -90,8 +93,8 @@ const follow = (restCtx, userId, callback) => { const unfollow = (restCtx, userId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/following/' + RestUtil.encodeURIComponent(userId) + '/unfollow', - 'POST', + `/api/following/${RestUtil.encodeURIComponent(userId)}/unfollow`, + HTTP_POST, null, callback ); diff --git a/lib/api.group.js b/lib/api.group.js index eae59b2..8b2e548 100644 --- a/lib/api.group.js +++ b/lib/api.group.js @@ -15,6 +15,16 @@ import * as CropAPI from './api.crop'; import * as RestUtil from './util'; +import { compose, not } from 'ramda'; + +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + +// Auxiliary functions +const isDefined = Boolean; +const isNotDefined = compose(not, isDefined); /** * Creates a group through the REST API. Optional arguments will only be added if they are defined @@ -40,7 +50,7 @@ const createGroup = (restCtx, displayName, description, visibility, joinable, ma managers, members }; - RestUtil.performRestRequest(restCtx, '/api/group/create', 'POST', postData, callback); + RestUtil.performRestRequest(restCtx, '/api/group/create', HTTP_POST, postData, callback); }; /** @@ -54,8 +64,8 @@ const createGroup = (restCtx, displayName, description, visibility, joinable, ma const deleteGroup = (restCtx, groupId, callback) => { return RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId), - 'DELETE', + `/api/group/${RestUtil.encodeURIComponent(groupId)}`, + HTTP_DELETE, null, callback ); @@ -72,8 +82,8 @@ const deleteGroup = (restCtx, groupId, callback) => { const restoreGroup = (restCtx, groupId, callback) => { return RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/restore', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/restore`, + HTTP_POST, null, callback ); @@ -89,7 +99,7 @@ const restoreGroup = (restCtx, groupId, callback) => { * @param {Group} callback.response The group object representing the requested group */ const getGroup = (restCtx, groupId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/group/' + RestUtil.encodeURIComponent(groupId), 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/group/${RestUtil.encodeURIComponent(groupId)}`, HTTP_GET, null, callback); }; /** @@ -110,8 +120,8 @@ const getGroup = (restCtx, groupId, callback) => { const updateGroup = (restCtx, groupId, profileFields, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId), - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}`, + HTTP_POST, profileFields, callback ); @@ -135,8 +145,8 @@ const getGroupMembers = (restCtx, groupId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/members', - 'GET', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/members`, + HTTP_GET, params, callback ); @@ -154,8 +164,8 @@ const getGroupMembers = (restCtx, groupId, start, limit, callback) => { const setGroupMembers = (restCtx, groupId, members, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/members', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/members`, + HTTP_POST, members, callback ); @@ -172,8 +182,8 @@ const setGroupMembers = (restCtx, groupId, members, callback) => { const joinGroup = (restCtx, groupId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/join', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/join`, + HTTP_POST, null, callback ); @@ -190,8 +200,8 @@ const joinGroup = (restCtx, groupId, callback) => { const leaveGroup = (restCtx, groupId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/leave', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/leave`, + HTTP_POST, null, callback ); @@ -215,8 +225,8 @@ const getMembershipsLibrary = (restCtx, userId, start, limit, callback) => { }; RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/memberships', - 'GET', + `/api/user/${RestUtil.encodeURIComponent(userId)}/memberships`, + HTTP_GET, params, callback ); @@ -239,16 +249,14 @@ const getMembershipsLibrary = (restCtx, userId, start, limit, callback) => { */ const uploadPicture = (restCtx, groupId, file, selectedArea, callback) => { const params = { file }; - if (selectedArea) { + if (isDefined(selectedArea)) { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/picture', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/picture`, + HTTP_POST, params, err => { - if (err) { - return callback(err); - } + if (err) return callback(err); CropAPI.cropPicture(restCtx, groupId, selectedArea, callback); } @@ -256,8 +264,8 @@ const uploadPicture = (restCtx, groupId, file, selectedArea, callback) => { } else { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/picture', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/picture`, + HTTP_POST, params, callback ); @@ -276,21 +284,17 @@ const uploadPicture = (restCtx, groupId, file, selectedArea, callback) => { * @param {Object} callback.picture The raw picture for this group. */ const downloadPicture = (restCtx, groupId, size, callback) => { - if (!size) { - return callback({ code: 400, msg: 'Missing size parameter' }); - } + if (isNotDefined(size)) return callback({ code: 400, msg: 'Missing size parameter' }); RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId), - 'GET', + `/api/group/${RestUtil.encodeURIComponent(groupId)}`, + HTTP_GET, null, (err, group) => { - if (err) { - return callback(err); - } + if (err) return callback(err); - if (!group.picture[size]) { + if (not(group.picture[size])) { return callback({ code: 404, msg: 'This group has no picture.' @@ -298,7 +302,7 @@ const downloadPicture = (restCtx, groupId, size, callback) => { } const url = group.picture[size]; - RestUtil.performRestRequest(restCtx, url, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, null, callback); } ); }; @@ -310,11 +314,11 @@ const downloadPicture = (restCtx, groupId, size, callback) => { * @param {String} groupId The group id that the user requested to join * @param {Function} callback Invoked when the mapping has been verified */ -const createRequestJoinGroup = function(restCtx, groupId, callback) { +const createRequestJoinGroup = (restCtx, groupId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/join-request', - 'POST', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/join-request`, + HTTP_POST, null, callback ); @@ -327,11 +331,11 @@ const createRequestJoinGroup = function(restCtx, groupId, callback) { * @param {String} groupId The group id that the user requested to join * @param {Function} callback Invoked when the mapping has been verified */ -const getJoinGroupRequest = function(restCtx, groupId, callback) { +const getJoinGroupRequest = (restCtx, groupId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/join-request/mine', - 'GET', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/join-request/mine`, + HTTP_GET, null, callback ); @@ -344,15 +348,15 @@ const getJoinGroupRequest = function(restCtx, groupId, callback) { * @param {String} groupId The group id that the user requested to join * @param {Function} callback Invoked when the mapping has been verified */ -const getJoinGroupRequests = function(restCtx, groupId, callback) { +const getJoinGroupRequests = (restCtx, groupId, callback) => { const params = { start: null, limit: null }; RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/join-request/all', - 'GET', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/join-request/all`, + HTTP_GET, params, callback ); @@ -368,7 +372,7 @@ const getJoinGroupRequests = function(restCtx, groupId, callback) { * @param {String} status The status of the request * @param {Function} callback Invoked when the mapping has been verified */ -const updateJoinGroupByRequest = function(restCtx, joinRequest, callback) { +const updateJoinGroupByRequest = (restCtx, joinRequest, callback) => { const { groupId, principalId, role, status } = joinRequest; const params = { principalId, @@ -377,8 +381,8 @@ const updateJoinGroupByRequest = function(restCtx, joinRequest, callback) { }; RestUtil.performRestRequest( restCtx, - '/api/group/' + RestUtil.encodeURIComponent(groupId) + '/join-request', - 'PUT', + `/api/group/${RestUtil.encodeURIComponent(groupId)}/join-request`, + HTTP_PUT, params, callback ); diff --git a/lib/api.invitations.js b/lib/api.invitations.js index d7b39d2..c2401a0 100644 --- a/lib/api.invitations.js +++ b/lib/api.invitations.js @@ -15,6 +15,9 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Get the invitations for the specified resource * @@ -28,13 +31,7 @@ import * as RestUtil from './util'; const getInvitations = (restCtx, resourceType, resourceId, callback) => { resourceType = RestUtil.encodeURIComponent(resourceType); resourceId = RestUtil.encodeURIComponent(resourceId); - RestUtil.performRestRequest( - restCtx, - '/api/' + resourceType + '/' + resourceId + '/invitations', - 'GET', - null, - callback - ); + RestUtil.performRestRequest(restCtx, `/api/${resourceType}/${resourceId}/invitations`, HTTP_GET, null, callback); }; /** @@ -53,8 +50,8 @@ const resendInvitation = (restCtx, resourceType, resourceId, email, callback) => email = RestUtil.encodeURIComponent(email); RestUtil.performRestRequest( restCtx, - '/api/' + resourceType + '/' + resourceId + '/invitations/' + email + '/resend', - 'POST', + `/api/${resourceType}/${resourceId}/invitations/${email}/resend`, + HTTP_POST, null, callback ); @@ -70,7 +67,7 @@ const resendInvitation = (restCtx, resourceType, resourceId, email, callback) => * @param {InvitationAcceptResult} callback.result The result of accepting the invitation, containing all resources to which the user became a member */ const acceptInvitation = (restCtx, token, callback) => { - RestUtil.performRestRequest(restCtx, '/api/invitation/accept', 'POST', { token }, callback); + RestUtil.performRestRequest(restCtx, '/api/invitation/accept', HTTP_POST, { token }, callback); }; export { getInvitations, resendInvitation, acceptInvitation }; diff --git a/lib/api.lti.js b/lib/api.lti.js index b2cf8e5..89a7823 100644 --- a/lib/api.lti.js +++ b/lib/api.lti.js @@ -15,6 +15,11 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + /** * Creates a LTI tool through the REST API. Optional arguments will only be added if they are defined * and will be sent as is. @@ -40,8 +45,8 @@ const createLtiTool = (restCtx, groupId, url, secret, key, displayName, descript }; RestUtil.performRestRequest( restCtx, - '/api/lti/' + RestUtil.encodeURIComponent(groupId) + '/create', - 'POST', + `/api/lti/${RestUtil.encodeURIComponent(groupId)}/create`, + HTTP_POST, postData, callback ); @@ -59,8 +64,8 @@ const createLtiTool = (restCtx, groupId, url, secret, key, displayName, descript const deleteLtiTool = (restCtx, groupId, toolId, callback) => { return RestUtil.performRestRequest( restCtx, - '/api/lti/' + RestUtil.encodeURIComponent(groupId) + '/' + RestUtil.encodeURIComponent(toolId), - 'DELETE', + `/api/lti/${RestUtil.encodeURIComponent(groupId)}/${RestUtil.encodeURIComponent(toolId)}`, + HTTP_DELETE, null, callback ); @@ -79,8 +84,8 @@ const deleteLtiTool = (restCtx, groupId, toolId, callback) => { const getLtiTool = (restCtx, groupId, toolId, callback) => { return RestUtil.performRestRequest( restCtx, - '/api/lti/' + RestUtil.encodeURIComponent(groupId) + '/' + RestUtil.encodeURIComponent(toolId), - 'GET', + `/api/lti/${RestUtil.encodeURIComponent(groupId)}/${RestUtil.encodeURIComponent(toolId)}`, + HTTP_GET, null, callback ); @@ -96,7 +101,7 @@ const getLtiTool = (restCtx, groupId, toolId, callback) => { * @param {LtiTool[]} callback.tools An array of LTI tool objects */ const getLtiTools = (restCtx, groupId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/lti/' + RestUtil.encodeURIComponent(groupId), 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/lti/${RestUtil.encodeURIComponent(groupId)}`, HTTP_GET, null, callback); }; export { createLtiTool, deleteLtiTool, getLtiTool, getLtiTools }; diff --git a/lib/api.mediacore.js b/lib/api.mediacore.js index 4e5c279..1647130 100644 --- a/lib/api.mediacore.js +++ b/lib/api.mediacore.js @@ -15,6 +15,9 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; + /** * Gets the embed code for a mediacore media item. * @@ -27,8 +30,8 @@ import * as RestUtil from './util'; const getEmbedCode = (restCtx, contentId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/mediacore/embed/' + RestUtil.encodeURIComponent(contentId), - 'GET', + `/api/mediacore/embed/${RestUtil.encodeURIComponent(contentId)}`, + HTTP_GET, null, callback ); @@ -38,13 +41,13 @@ const getEmbedCode = (restCtx, contentId, callback) => { * Notify the server that encoding for a particular media item has completed. * * @param {RestContext} restCtx Standard REST Context object that contains the current tenant URL and the current user credentials - * @param {String} mediaCoreId The id of the mediacore item whose encoding has just completed + * @param {String} mediaId The id of the mediacore item whose encoding has just completed * @param {Object} callback.err Error object containing error code and error message */ -const notifyEncodingComplete = (restCtx, mediaCoreId, callback) => { +const notifyEncodingComplete = (restCtx, mediaId, callback) => { // The parameter convention on this differs a bit from the rest of the application because it is molded according to // mediacore's spec. It cannot change to become more consistent - RestUtil.performRestRequest(restCtx, '/api/mediacore/encodingCallback', 'POST', { mediaId: mediaCoreId }, callback); + RestUtil.performRestRequest(restCtx, '/api/mediacore/encodingCallback', HTTP_POST, { mediaId: mediaId }, callback); }; export { getEmbedCode, notifyEncodingComplete }; diff --git a/lib/api.meetings-jitsi.js b/lib/api.meetings-jitsi.js index f4fb494..a773b05 100644 --- a/lib/api.meetings-jitsi.js +++ b/lib/api.meetings-jitsi.js @@ -17,6 +17,11 @@ import * as RestUtil from './util'; const API_ENDPOINT = '/api/meeting-jitsi'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + /** * Create a new meeting through the REST API. * @@ -32,7 +37,7 @@ const API_ENDPOINT = '/api/meeting-jitsi'; * @param {Object} callback.err Error object containing error code and error message * @param {Meeting} callback.meeting Meeting object representing the created meeting */ -const createMeeting = function( +const createMeeting = ( restCtx, displayName, description, @@ -42,7 +47,7 @@ const createMeeting = function( managers, members, callback -) { +) => { const params = { displayName, description, @@ -52,7 +57,7 @@ const createMeeting = function( managers, members }; - RestUtil.performRestRequest(restCtx, API_ENDPOINT + '/create', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/create`, HTTP_POST, params, callback); }; /** @@ -66,15 +71,15 @@ const createMeeting = function( * @param {Object} callback.err Error object containing error code and error message * @param {User[]|Group[]} callback.members Array that contains an object for each member. Each object has a role property that contains the role of the member and a profile property that contains the principal profile of the member */ -const getMembers = function(restCtx, meetingId, start, limit, callback) { +const getMembers = (restCtx, meetingId, start, limit, callback) => { const params = { start, limit }; RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId) + '/members', - 'GET', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}/members`, + HTTP_GET, params, callback ); @@ -90,11 +95,11 @@ const getMembers = function(restCtx, meetingId, start, limit, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Meeting} callback.meeting The updated meeting object */ -const updateMeeting = function(restCtx, meetingId, params, callback) { +const updateMeeting = (restCtx, meetingId, params, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId), - 'PUT', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}`, + HTTP_PUT, params, callback ); @@ -108,11 +113,11 @@ const updateMeeting = function(restCtx, meetingId, params, callback) { * @param {Function} callback Standard callback method * @param {Object} callback.err Error object containing error code and error message */ -const deleteMeeting = function(restCtx, meetingId, callback) { +const deleteMeeting = (restCtx, meetingId, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId), - 'DELETE', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}`, + HTTP_DELETE, null, callback ); @@ -127,11 +132,11 @@ const deleteMeeting = function(restCtx, meetingId, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Meeting} callback.meeting The updated meeting object */ -const getMeeting = function(restCtx, meetingId, callback) { +const getMeeting = (restCtx, meetingId, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId), - 'GET', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}`, + HTTP_GET, null, callback ); @@ -146,11 +151,11 @@ const getMeeting = function(restCtx, meetingId, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Meeting[]} callback.meeting The updated meeting object */ -const getMeetingsLibrary = function(restCtx, principalId, callback) { +const getMeetingsLibrary = (restCtx, principalId, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/library/' + RestUtil.encodeURIComponent(principalId), - 'GET', + `${API_ENDPOINT}/library/${RestUtil.encodeURIComponent(principalId)}`, + HTTP_GET, null, callback ); @@ -165,11 +170,11 @@ const getMeetingsLibrary = function(restCtx, principalId, callback) { * @param {Function} callback Standard callback method * @param {Object} callback.err Error object containing error code and error message */ -const updateMembers = function(restCtx, meetingId, updatedMembers, callback) { +const updateMembers = (restCtx, meetingId, updatedMembers, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId) + '/members', - 'PUT', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}/members`, + HTTP_PUT, updatedMembers, callback ); @@ -186,11 +191,11 @@ const updateMembers = function(restCtx, meetingId, updatedMembers, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Comment} callback.comment The created comment */ -const createComment = function(restCtx, meetingId, body, replyTo, callback) { +const createComment = (restCtx, meetingId, body, replyTo, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId) + '/messages', - 'POST', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}/messages`, + HTTP_POST, { body, replyTo @@ -209,11 +214,11 @@ const createComment = function(restCtx, meetingId, body, replyTo, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Comment} callback.softDeleted If the comment is not deleted, but instead flagged as deleted because it has replies, this will return a stripped down comment object representing the deleted comment, with the `deleted` parameter set to `false`. If the comment has been properly deleted, no comment will be returned. */ -const deleteComment = function(restCtx, meetingId, created, callback) { +const deleteComment = (restCtx, meetingId, created, callback) => { RestUtil.performRestRequest( restCtx, - API_ENDPOINT + '/' + RestUtil.encodeURIComponent(meetingId) + '/messages/' + RestUtil.encodeURIComponent(created), - 'DELETE', + `${API_ENDPOINT}/${RestUtil.encodeURIComponent(meetingId)}/messages/${RestUtil.encodeURIComponent(created)}`, + HTTP_DELETE, null, callback ); diff --git a/lib/api.meetups.js b/lib/api.meetups.js index 2262bb7..2fb97fb 100644 --- a/lib/api.meetups.js +++ b/lib/api.meetups.js @@ -17,6 +17,11 @@ import * as RestUtil from './util'; const API_ENDPOINT = '/api/meetups'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + /** * Create a new meetup through the REST API. * @@ -26,7 +31,7 @@ const API_ENDPOINT = '/api/meetups'; * @param {Object} callback.err Error object containing error code and error message */ const joinMeetup = (restCtx, groupId, callback) => { - RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/join`, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/join`, HTTP_GET, null, callback); }; /** @@ -38,7 +43,7 @@ const joinMeetup = (restCtx, groupId, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const endMeetup = (restCtx, groupId, callback) => { - RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/end`, 'POST', null, callback); + RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/end`, HTTP_POST, null, callback); }; /** @@ -51,7 +56,7 @@ const endMeetup = (restCtx, groupId, callback) => { * @param {Boolean} callback.isStillRunning Boolean specifying whether the meetup is still running */ const isMeetingRunning = (restCtx, groupId, callback) => { - RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/isMeetingRunning`, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `${API_ENDPOINT}/${groupId}/isMeetingRunning`, HTTP_GET, null, callback); }; /** @@ -67,7 +72,7 @@ const createMeetupRecordingLink = (restCtx, groupId, signedParameters, callback) RestUtil.performRestRequest( restCtx, `${API_ENDPOINT}/${groupId}/recording`, - 'POST', + HTTP_POST, { signedParameters }, diff --git a/lib/api.oauth.js b/lib/api.oauth.js index 72d4e58..4e1ef7c 100644 --- a/lib/api.oauth.js +++ b/lib/api.oauth.js @@ -15,6 +15,11 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + /** * Create an OAuth Client * @@ -28,8 +33,8 @@ import * as RestUtil from './util'; const createClient = (restCtx, userId, displayName, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/oauth/clients/' + RestUtil.encodeURIComponent(userId), - 'POST', + `/api/auth/oauth/clients/${RestUtil.encodeURIComponent(userId)}`, + HTTP_POST, { displayName }, callback ); @@ -47,8 +52,8 @@ const createClient = (restCtx, userId, displayName, callback) => { const getClients = (restCtx, userId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/auth/oauth/clients/' + RestUtil.encodeURIComponent(userId), - 'GET', + `/api/auth/oauth/clients/${RestUtil.encodeURIComponent(userId)}`, + HTTP_GET, null, callback ); @@ -66,13 +71,12 @@ const getClients = (restCtx, userId, callback) => { * @param {Object} callback.err Standard error object, if any */ const updateClient = (restCtx, userId, clientId, displayName, secret, callback) => { - const url = - '/api/auth/oauth/clients/' + RestUtil.encodeURIComponent(userId) + '/' + RestUtil.encodeURIComponent(clientId); + const url = `/api/auth/oauth/clients/${RestUtil.encodeURIComponent(userId)}/${RestUtil.encodeURIComponent(clientId)}`; const params = { displayName, secret }; - RestUtil.performRestRequest(restCtx, url, 'POST', params, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, callback); }; /** @@ -85,8 +89,7 @@ const updateClient = (restCtx, userId, clientId, displayName, secret, callback) * @param {Object} callback.err Standard error object, if any */ const deleteClient = (restCtx, userId, clientId, callback) => { - const url = - '/api/auth/oauth/clients/' + RestUtil.encodeURIComponent(userId) + '/' + RestUtil.encodeURIComponent(clientId); + const url = `/api/auth/oauth/clients/${RestUtil.encodeURIComponent(userId)}/${RestUtil.encodeURIComponent(clientId)}`; RestUtil.performRestRequest(restCtx, url, 'DELETE', null, callback); }; diff --git a/lib/api.previews.js b/lib/api.previews.js index 7cdd06c..6341ea0 100644 --- a/lib/api.previews.js +++ b/lib/api.previews.js @@ -15,6 +15,11 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + /** * Reprocess the preview of a revision of a particular content item. * @@ -29,8 +34,8 @@ const reprocessPreview = (restCtx, contentId, revisionId, callback) => { revisionId = RestUtil.encodeURIComponent(revisionId); RestUtil.performRestRequest( restCtx, - '/api/content/' + contentId + '/revision/' + revisionId + '/reprocessPreview', - 'POST', + `/api/content/${contentId}/revision/${revisionId}/reprocessPreview`, + HTTP_POST, null, callback ); @@ -59,7 +64,7 @@ const reprocessPreview = (restCtx, contentId, revisionId, callback) => { * @param {Function} callback Invoked when the request completes. The actuall reprocessing happens async */ const reprocessPreviews = (globalAdminRestContext, filters, callback) => { - RestUtil.performRestRequest(globalAdminRestContext, '/api/content/reprocessPreviews', 'POST', filters, callback); + RestUtil.performRestRequest(globalAdminRestContext, '/api/content/reprocessPreviews', HTTP_POST, filters, callback); }; /** @@ -76,7 +81,7 @@ const expandUrl = (restCtx, url, callback) => { const data = { url: RestUtil.encodeURIComponent(url) }; - RestUtil.performRestRequest(restCtx, '/api/longurl/expand', 'GET', data, callback); + RestUtil.performRestRequest(restCtx, '/api/longurl/expand', HTTP_GET, data, callback); }; export { reprocessPreview, reprocessPreviews, expandUrl }; diff --git a/lib/api.search.js b/lib/api.search.js index 8de76d1..f8b3aeb 100644 --- a/lib/api.search.js +++ b/lib/api.search.js @@ -13,8 +13,13 @@ * permissions and limitations under the License. */ -import _ from 'underscore'; import * as RestUtil from './util'; +import { defaultTo, map, join } from 'ramda'; + +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; /** * Perform a search. @@ -32,21 +37,19 @@ import * as RestUtil from './util'; * @param {SearchResult} callback.result SearchResult object representing the search result */ const search = (restCtx, searchType, params, opts, callback) => { - params = params || []; - opts = opts || {}; + params = defaultTo([], params); + opts = defaultTo({}, opts); // Url-encode and join the path parameters into a path string - params = _.map(params, param => { - return RestUtil.encodeURIComponent(param); - }); - params = params.join('/'); + params = map(param => RestUtil.encodeURIComponent(param), params); + params = join('/', params); - let path = '/api/search/' + RestUtil.encodeURIComponent(searchType); + let path = `/api/search/${RestUtil.encodeURIComponent(searchType)}`; if (params) { - path += '/' + params; + path += `/${params}`; } - RestUtil.performRestRequest(restCtx, path, 'GET', opts, callback); + RestUtil.performRestRequest(restCtx, path, HTTP_GET, opts, callback); }; /** @@ -58,7 +61,7 @@ const search = (restCtx, searchType, params, opts, callback) => { * @param {Object} callback.err An error that occurred, if any */ const refresh = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/search/_refresh', 'POST', null, callback); + RestUtil.performRestRequest(restCtx, '/api/search/_refresh', HTTP_POST, null, callback); }; /** @@ -69,7 +72,7 @@ const refresh = (restCtx, callback) => { * @param {Object} callback.err An error that occurred, if any */ const reindexAll = (globalAdminRestCtx, callback) => { - RestUtil.performRestRequest(globalAdminRestCtx, '/api/search/reindexAll', 'POST', null, callback); + RestUtil.performRestRequest(globalAdminRestCtx, '/api/search/reindexAll', HTTP_POST, null, callback); }; export { search, refresh, reindexAll }; diff --git a/lib/api.telemetry.js b/lib/api.telemetry.js index d5a3414..02cc292 100644 --- a/lib/api.telemetry.js +++ b/lib/api.telemetry.js @@ -15,6 +15,8 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; + /** * Function that returns telemetry data * @@ -24,7 +26,7 @@ import * as RestUtil from './util'; * @param {Object} callback.record The telemetry data */ const getTelemetryData = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/telemetry', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/telemetry', HTTP_GET, null, callback); }; export { getTelemetryData }; diff --git a/lib/api.tenants.js b/lib/api.tenants.js index 6dbd508..e633d27 100644 --- a/lib/api.tenants.js +++ b/lib/api.tenants.js @@ -15,6 +15,13 @@ import * as RestUtil from './util'; +import { defaultTo } from 'ramda'; + +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + // Stopping a server is async, this variable holds how long we should wait before returning on // start/stop/delete of a tenant const WAIT_TIME = 100; @@ -33,7 +40,7 @@ const WAIT_TIME = 100; * @param {TenantNetwork} callback.tenantNetwork The tenant network that was created */ const createTenantNetwork = (restCtx, displayName, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenantNetwork/create', 'POST', { displayName }, callback); + RestUtil.performRestRequest(restCtx, '/api/tenantNetwork/create', HTTP_POST, { displayName }, callback); }; /** @@ -45,7 +52,7 @@ const createTenantNetwork = (restCtx, displayName, callback) => { * @param {Object} callback.tenantNetworks All tenant networks in the system, keyed by their tenant network id */ const getTenantNetworks = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenantNetworks', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/tenantNetworks', HTTP_GET, null, callback); }; /** @@ -61,8 +68,8 @@ const getTenantNetworks = (restCtx, callback) => { const updateTenantNetwork = (restCtx, id, displayName, callback) => { RestUtil.performRestRequest( restCtx, - '/api/tenantNetwork/' + RestUtil.encodeURIComponent(id), - 'POST', + `/api/tenantNetwork/${RestUtil.encodeURIComponent(id)}`, + HTTP_POST, { displayName }, callback ); @@ -79,8 +86,8 @@ const updateTenantNetwork = (restCtx, id, displayName, callback) => { const deleteTenantNetwork = (restCtx, id, callback) => { RestUtil.performRestRequest( restCtx, - '/api/tenantNetwork/' + RestUtil.encodeURIComponent(id), - 'DELETE', + `/api/tenantNetwork/${RestUtil.encodeURIComponent(id)}`, + HTTP_DELETE, null, callback ); @@ -98,8 +105,8 @@ const deleteTenantNetwork = (restCtx, id, callback) => { const addTenantAliases = (restCtx, tenantNetworkId, tenantAliases, callback) => { RestUtil.performRestRequest( restCtx, - '/api/tenantNetwork/' + RestUtil.encodeURIComponent(tenantNetworkId) + '/addTenants', - 'POST', + `/api/tenantNetwork/${RestUtil.encodeURIComponent(tenantNetworkId)}/addTenants`, + HTTP_POST, { alias: tenantAliases }, callback ); @@ -117,16 +124,16 @@ const addTenantAliases = (restCtx, tenantNetworkId, tenantAliases, callback) => const removeTenantAliases = (restCtx, tenantNetworkId, tenantAliases, callback) => { RestUtil.performRestRequest( restCtx, - '/api/tenantNetwork/' + RestUtil.encodeURIComponent(tenantNetworkId) + '/removeTenants', - 'POST', + `/api/tenantNetwork/${RestUtil.encodeURIComponent(tenantNetworkId)}/removeTenants`, + HTTP_POST, { alias: tenantAliases }, callback ); }; -/// ////////// -// TENANTS // -/// ////////// +/** + * Tenants + */ /** * Retrieve all available tenants through the REST API. @@ -137,7 +144,7 @@ const removeTenantAliases = (restCtx, tenantNetworkId, tenantAliases, callback) * @param {Tenant[]} callback.tenants Array containing a tenant object for each of the available tenants */ const getTenants = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenants', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/tenants', HTTP_GET, null, callback); }; /** @@ -151,7 +158,7 @@ const getTenants = (restCtx, callback) => { */ const getTenantsByEmailAddress = (restCtx, emails, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenantsByEmail', 'GET', { emails }, callback); + RestUtil.performRestRequest(restCtx, '/api/tenantsByEmail', HTTP_GET, { emails }, callback); }; /** @@ -166,10 +173,10 @@ const getTenantsByEmailAddress = (restCtx, emails, callback) => { const getTenant = (restCtx, alias, callback) => { let url = '/api/tenant'; if (alias) { - url += '/' + RestUtil.encodeURIComponent(alias); + url += `/${RestUtil.encodeURIComponent(alias)}`; } - RestUtil.performRestRequest(restCtx, url, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, null, callback); }; /** @@ -187,7 +194,7 @@ const getTenant = (restCtx, alias, callback) => { * @param {Tenant} callback.tenant Tenant object representing the newly created tenant */ const createTenant = (restCtx, alias, displayName, host, opts, callback) => { - opts = opts || {}; + opts = defaultTo({}, opts); const params = { alias, displayName, @@ -195,10 +202,8 @@ const createTenant = (restCtx, alias, displayName, host, opts, callback) => { emailDomains: opts.emailDomains, countryCode: opts.countryCode }; - RestUtil.performRestRequest(restCtx, '/api/tenant/create', 'POST', params, (err, tenant) => { - if (err) { - return callback(err); - } + RestUtil.performRestRequest(restCtx, '/api/tenant/create', HTTP_POST, params, (err, tenant) => { + if (err) return callback(err); // Give the tenant some time to start return setTimeout(callback, WAIT_TIME, err, tenant); @@ -219,11 +224,11 @@ const createTenant = (restCtx, alias, displayName, host, opts, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const updateTenant = (restCtx, alias, tenantUpdates, callback) => { - tenantUpdates = tenantUpdates || {}; + tenantUpdates = defaultTo({}, tenantUpdates); let url = '/api/tenant'; if (alias) { - url += '/' + RestUtil.encodeURIComponent(alias); + url += `/${RestUtil.encodeURIComponent(alias)}`; } const params = { @@ -232,7 +237,7 @@ const updateTenant = (restCtx, alias, tenantUpdates, callback) => { emailDomains: tenantUpdates.emailDomains, countryCode: tenantUpdates.countryCode }; - RestUtil.performRestRequest(restCtx, url, 'POST', params, err => { + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, err => { if (err) { callback(err); } else { @@ -251,7 +256,7 @@ const updateTenant = (restCtx, alias, tenantUpdates, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const stopTenant = (restCtx, alias, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenant/stop', 'POST', { aliases: [alias] }, err => { + RestUtil.performRestRequest(restCtx, '/api/tenant/stop', HTTP_POST, { aliases: [alias] }, err => { if (err) { callback(err); } else { @@ -270,7 +275,7 @@ const stopTenant = (restCtx, alias, callback) => { * @param {Object} callback.err Error object containing error code and error message */ const startTenant = (restCtx, tenantAlias, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenant/start', 'POST', { aliases: [tenantAlias] }, err => { + RestUtil.performRestRequest(restCtx, '/api/tenant/start', HTTP_POST, { aliases: [tenantAlias] }, err => { if (err) { callback(err); } else { @@ -289,7 +294,7 @@ const startTenant = (restCtx, tenantAlias, callback) => { * @param {Object[]} callback.landingPage The landing page information */ const getLandingPage = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/tenant/landingPage', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/tenant/landingPage', HTTP_GET, null, callback); }; export { diff --git a/lib/api.ui.js b/lib/api.ui.js index b10fa7e..1ac906a 100644 --- a/lib/api.ui.js +++ b/lib/api.ui.js @@ -14,6 +14,14 @@ */ import * as RestUtil from './util'; +import { compose, not, is } from 'ramda'; + +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + +const isNotArray = compose(not, is(Array)); /** * Get all of the widget manifest files through the REST API. @@ -24,7 +32,7 @@ import * as RestUtil from './util'; * @param {Object} callback.manifests The aggregated widget manifest files where the keys represent the widget ids and the values contain the widget manifest. */ const getWidgetManifests = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/ui/widgets', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/ui/widgets', HTTP_GET, null, callback); }; /** @@ -37,11 +45,11 @@ const getWidgetManifests = (restCtx, callback) => { * @param {String[]} callback.data Array containing the file content for the requested static files. */ const getStaticBatch = (restCtx, files, callback) => { - if (!Array.isArray(files)) { + if (isNotArray(files)) { files = [files]; } - RestUtil.performRestRequest(restCtx, '/api/ui/staticbatch', 'GET', { files }, callback); + RestUtil.performRestRequest(restCtx, '/api/ui/staticbatch', HTTP_GET, { files }, callback); }; /** @@ -52,8 +60,8 @@ const getStaticBatch = (restCtx, files, callback) => { * @param {Object} callback.err Error object containing error code and error message * @param {String} callback.css The skin file for this tenant (in CSS). */ -const getSkin = function(restCtx, callback) { - RestUtil.performRestRequest(restCtx, '/api/ui/skin', 'GET', null, callback); +const getSkin = (restCtx, callback) => { + RestUtil.performRestRequest(restCtx, '/api/ui/skin', HTTP_GET, null, callback); }; /** @@ -64,8 +72,8 @@ const getSkin = function(restCtx, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {String} callback.css The URL String for the logo of this tenant. */ -const getLogo = function(restCtx, callback) { - RestUtil.performRestRequest(restCtx, '/api/ui/logo', 'GET', null, callback); +const getLogo = (restCtx, callback) => { + RestUtil.performRestRequest(restCtx, '/api/ui/logo', HTTP_GET, null, callback); }; /** @@ -77,8 +85,8 @@ const getLogo = function(restCtx, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Object} callback.variables The variables grouped by their respective groups. */ -const getSkinVariables = function(restCtx, tenantAlias, callback) { - RestUtil.performRestRequest(restCtx, '/api/ui/skin/variables', 'GET', { tenant: tenantAlias }, callback); +const getSkinVariables = (restCtx, tenantAlias, callback) => { + RestUtil.performRestRequest(restCtx, '/api/ui/skin/variables', HTTP_GET, { tenant: tenantAlias }, callback); }; /** @@ -91,12 +99,12 @@ const getSkinVariables = function(restCtx, tenantAlias, callback) { * @param {Object} callback.err Error object containing error code and error message * @param {Object} callback.url The variables grouped by their respective groups. */ -const uploadLogo = function(restCtx, file, tenantAlias, callback) { +const uploadLogo = (restCtx, file, tenantAlias, callback) => { const params = { file, tenantAlias }; - RestUtil.performRestRequest(restCtx, '/api/ui/skin/logo', 'POST', params, callback); + RestUtil.performRestRequest(restCtx, '/api/ui/skin/logo', HTTP_POST, params, callback); }; export { getWidgetManifests, getStaticBatch, getSkin, getLogo, getSkinVariables, uploadLogo }; diff --git a/lib/api.user.js b/lib/api.user.js index 1e0671c..9db3245 100644 --- a/lib/api.user.js +++ b/lib/api.user.js @@ -14,10 +14,21 @@ */ import _ from 'underscore'; +import { defaultTo, not, compose, equals, mergeAll } from 'ramda'; import * as CropAPI from './api.crop'; import * as RestUtil from './util'; +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + +// Auxiliary functions +const isDefined = Boolean; +const isNotDefined = compose(not, isDefined); +const isTrue = equals(true); + /** * Create a global administrator user with mapped local authentication credentials in the system * @@ -32,14 +43,18 @@ import * as RestUtil from './util'; * @param {User} callback.user The user object that was created */ const createGlobalAdminUser = (restCtx, username, password, displayName, email, opts, callback) => { - opts = _.extend({}, opts, { - username, - password, - displayName, - email - }); + opts = mergeAll([ + {}, + opts, + { + username, + password, + displayName, + email + } + ]); - RestUtil.performRestRequest(restCtx, '/api/user/createGlobalAdminUser', 'POST', opts, callback); + RestUtil.performRestRequest(restCtx, '/api/user/createGlobalAdminUser', HTTP_POST, opts, callback); }; /** @@ -57,21 +72,26 @@ const createGlobalAdminUser = (restCtx, username, password, displayName, email, * @param {User} callback.user The user object that was created * @api private */ -const _createTenantAdminUser = function(restCtx, tenantAlias, username, password, displayName, email, opts, callback) { - opts = opts || {}; - const params = _.extend({}, opts, { - username, - password, - displayName, - email - }); +const _createTenantAdminUser = (restCtx, tenantAlias, ...args) => { + let [username, password, displayName, email, opts, callback] = args; + opts = defaultTo({}, opts); + const params = mergeAll([ + {}, + opts, + { + username, + password, + displayName, + email + } + ]); let url = '/api/user/createTenantAdminUser'; if (tenantAlias) { - url = '/api/user/' + RestUtil.encodeURIComponent(tenantAlias) + '/createTenantAdminUser'; + url = `/api/user/${RestUtil.encodeURIComponent(tenantAlias)}/createTenantAdminUser`; } - RestUtil.performRestRequest(restCtx, url, 'POST', params, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, callback); }; /** @@ -87,8 +107,8 @@ const _createTenantAdminUser = function(restCtx, tenantAlias, username, password * @param {Object} callback.err An error that occurred, if any * @param {User} callback.user The user object that was created */ -const createTenantAdminUser = (restCtx, username, password, displayName, email, opts, callback) => { - _createTenantAdminUser(restCtx, null, username, password, displayName, email, opts, callback); +const createTenantAdminUser = (restCtx, ...args) => { + _createTenantAdminUser(restCtx, null, ...args); }; /** @@ -105,17 +125,8 @@ const createTenantAdminUser = (restCtx, username, password, displayName, email, * @param {Object} callback.err An error that occurred, if any * @param {User} callback.user The user object that was created */ -const createTenantAdminUserOnTenant = ( - restCtx, - tenantAlias, - username, - password, - displayName, - email, - opts, - callback -) => { - _createTenantAdminUser(restCtx, tenantAlias, username, password, displayName, email, opts, callback); +const createTenantAdminUserOnTenant = (restCtx, tenantAlias, ...args) => { + _createTenantAdminUser(restCtx, tenantAlias, ...args); }; /** @@ -138,21 +149,26 @@ const createTenantAdminUserOnTenant = ( * @param {User} callback.response A User object representing the created user * @api private */ -const _createUser = function(restCtx, tenantAlias, username, password, displayName, email, opts, callback) { - opts = opts || {}; - const params = _.extend({}, opts, { - username, - password, - displayName, - email - }); +const _createUser = (restCtx, tenantAlias, ...args) => { + let [username, password, displayName, email, opts, callback] = args; + opts = defaultTo({}, opts); + const params = mergeAll([ + {}, + opts, + { + username, + password, + displayName, + email + } + ]); let url = '/api/user/create'; if (tenantAlias) { - url = '/api/user/' + RestUtil.encodeURIComponent(tenantAlias) + '/create'; + url = `/api/user/${RestUtil.encodeURIComponent(tenantAlias)}/create`; } - RestUtil.performRestRequest(restCtx, url, 'POST', params, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_POST, params, callback); }; /** @@ -173,8 +189,8 @@ const _createUser = function(restCtx, tenantAlias, username, password, displayNa * @param {Object} callback.err An error that occurred, if any * @param {User} callback.response A User object representing the created user */ -const createUser = (restCtx, username, password, displayName, email, opts, callback) => { - _createUser(restCtx, null, username, password, displayName, email, opts, callback); +const createUser = (restCtx, ...args) => { + _createUser(restCtx, null, ...args); }; /** @@ -186,7 +202,7 @@ const createUser = (restCtx, username, password, displayName, email, opts, callb * @param {Object} callback.err An error that occurred, if any */ const deleteUser = (restCtx, userId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/user/' + RestUtil.encodeURIComponent(userId), 'DELETE', null, callback); + RestUtil.performRestRequest(restCtx, `/api/user/${RestUtil.encodeURIComponent(userId)}`, HTTP_DELETE, null, callback); }; /** @@ -200,8 +216,8 @@ const deleteUser = (restCtx, userId, callback) => { const restoreUser = (restCtx, userId, callback) => { RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/restore', - 'POST', + `/api/user/${RestUtil.encodeURIComponent(userId)}/restore`, + HTTP_POST, null, callback ); @@ -226,8 +242,8 @@ const restoreUser = (restCtx, userId, callback) => { * @param {Object} callback.err An error that occurred, if any * @param {User} callback.response A User object representing the created user */ -const createUserOnTenant = (restCtx, tenantAlias, username, password, displayName, email, opts, callback) => { - _createUser(restCtx, tenantAlias, username, password, displayName, email, opts, callback); +const createUserOnTenant = (restCtx, tenantAlias, ...args) => { + _createUser(restCtx, tenantAlias, ...args); }; /** @@ -239,7 +255,7 @@ const createUserOnTenant = (restCtx, tenantAlias, username, password, displayNam * @param {Object} callback.response The user's me feed */ const getMe = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/me', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/me', HTTP_GET, null, callback); }; /** @@ -252,7 +268,7 @@ const getMe = (restCtx, callback) => { * @param {User} callback.response The user's basic profile */ const getUser = (restCtx, userId, callback) => { - RestUtil.performRestRequest(restCtx, '/api/user/' + RestUtil.encodeURIComponent(userId), 'GET', null, callback); + RestUtil.performRestRequest(restCtx, `/api/user/${RestUtil.encodeURIComponent(userId)}`, HTTP_GET, null, callback); }; /** @@ -265,7 +281,7 @@ const getUser = (restCtx, userId, callback) => { * @param {Object} callback.err Standard error object, if any */ const updateUser = (restCtx, userId, params, callback) => { - RestUtil.performRestRequest(restCtx, '/api/user/' + RestUtil.encodeURIComponent(userId), 'POST', params, callback); + RestUtil.performRestRequest(restCtx, `/api/user/${RestUtil.encodeURIComponent(userId)}`, HTTP_POST, params, callback); }; /** @@ -287,16 +303,14 @@ const uploadPicture = (restCtx, userId, file, selectedArea, callback) => { const params = { file }; - if (selectedArea) { + if (isDefined(selectedArea)) { RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/picture', - 'POST', + `/api/user/${RestUtil.encodeURIComponent(userId)}/picture`, + HTTP_POST, params, err => { - if (err) { - return callback(err); - } + if (err) return callback(err); CropAPI.cropPicture(restCtx, userId, selectedArea, callback); } @@ -304,8 +318,8 @@ const uploadPicture = (restCtx, userId, file, selectedArea, callback) => { } else { RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/picture', - 'POST', + `/api/user/${RestUtil.encodeURIComponent(userId)}/picture`, + HTTP_POST, params, callback ); @@ -324,21 +338,19 @@ const uploadPicture = (restCtx, userId, file, selectedArea, callback) => { * @param {Object} callback.picture The raw picture for this group */ const downloadPicture = (restCtx, userId, size, callback) => { - if (!size) { + if (isNotDefined(size)) { return callback({ code: 400, msg: 'Missing size parameter' }); } getUser(restCtx, userId, (err, user) => { - if (err) { - return callback(err); - } + if (err) return callback(err); - if (!user.picture[size]) { + if (isNotDefined(user.picture[size])) { return callback({ code: 404, msg: 'This user has no picture.' }); } const url = user.picture[size]; - RestUtil.performRestRequest(restCtx, url, 'GET', null, callback); + RestUtil.performRestRequest(restCtx, url, HTTP_GET, null, callback); }); }; @@ -354,9 +366,9 @@ const downloadPicture = (restCtx, userId, size, callback) => { const setTenantAdmin = (restCtx, userId, value, callback) => { RestUtil.performRestRequest( restCtx, - '/api/user/' + RestUtil.encodeURIComponent(userId) + '/admin', - 'POST', - { admin: value === true }, + `/api/user/${RestUtil.encodeURIComponent(userId)}/admin`, + HTTP_POST, + { admin: isTrue(value) }, callback ); }; @@ -369,7 +381,7 @@ const setTenantAdmin = (restCtx, userId, value, callback) => { * @param {Object} callback.err Standard error object, if any */ const getTimezones = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/timezones', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/timezones', HTTP_GET, null, callback); }; /** @@ -382,7 +394,7 @@ const getTimezones = (restCtx, callback) => { * @param {Object} callback.err Standard error object, if any */ const getTermsAndConditions = (restCtx, locale, callback) => { - RestUtil.performRestRequest(restCtx, '/api/user/termsAndConditions', 'GET', { locale }, callback); + RestUtil.performRestRequest(restCtx, '/api/user/termsAndConditions', HTTP_GET, { locale }, callback); }; /** @@ -395,8 +407,8 @@ const getTermsAndConditions = (restCtx, locale, callback) => { * @param {User} callback.user The updated user object */ const acceptTermsAndConditions = (restCtx, userId, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/termsAndConditions'; - RestUtil.performRestRequest(restCtx, url, 'POST', {}, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/termsAndConditions`; + RestUtil.performRestRequest(restCtx, url, HTTP_POST, {}, callback); }; /** @@ -409,8 +421,8 @@ const acceptTermsAndConditions = (restCtx, userId, callback) => { * @param {Object} callback.err An error that occurred, if any */ const verifyEmail = (restCtx, userId, token, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/email/verify'; - RestUtil.performRestRequest(restCtx, url, 'POST', { token }, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/email/verify`; + RestUtil.performRestRequest(restCtx, url, HTTP_POST, { token }, callback); }; /** @@ -422,8 +434,8 @@ const verifyEmail = (restCtx, userId, token, callback) => { * @param {Object} callback.err An error that occurred, if any */ const resendEmailToken = (restCtx, userId, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/email/resend'; - RestUtil.performRestRequest(restCtx, url, 'POST', {}, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/email/resend`; + RestUtil.performRestRequest(restCtx, url, HTTP_POST, {}, callback); }; /** @@ -436,8 +448,8 @@ const resendEmailToken = (restCtx, userId, callback) => { * @param {String} callback.email The email address for which there is a token */ const getEmailToken = (restCtx, userId, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/email/token'; - RestUtil.performRestRequest(restCtx, url, 'GET', {}, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/email/token`; + RestUtil.performRestRequest(restCtx, url, HTTP_GET, {}, callback); }; /** @@ -449,8 +461,8 @@ const getEmailToken = (restCtx, userId, callback) => { * @param {Object} callback.err An error that occurred, if any */ const deleteEmailToken = (restCtx, userId, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/email/token'; - RestUtil.performRestRequest(restCtx, url, 'DELETE', {}, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/email/token`; + RestUtil.performRestRequest(restCtx, url, HTTP_DELETE, {}, callback); }; /** @@ -463,8 +475,8 @@ const deleteEmailToken = (restCtx, userId, callback) => { * @param {Group[]} callback.response The user's most recently visited groups */ const getRecentlyVisitedGroups = (restCtx, userId, callback) => { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/groups/recent'; - RestUtil.performRestRequest(restCtx, url, 'GET', {}, callback); + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/groups/recent`; + RestUtil.performRestRequest(restCtx, url, HTTP_GET, {}, callback); }; /** @@ -478,9 +490,9 @@ const getRecentlyVisitedGroups = (restCtx, userId, callback) => { * @param {Zip} callback.zip Zip file containing all personal data of a user * @api private */ -const exportPersonalData = function(restCtx, userId, exportType, callback) { - const url = '/api/user/' + RestUtil.encodeURIComponent(userId) + '/export/' + RestUtil.encodeURIComponent(exportType); - RestUtil.performRestRequest(restCtx, url, 'GET', {}, callback); +const exportPersonalData = (restCtx, userId, exportType, callback) => { + const url = `/api/user/${RestUtil.encodeURIComponent(userId)}/export/${RestUtil.encodeURIComponent(exportType)}`; + RestUtil.performRestRequest(restCtx, url, HTTP_GET, {}, callback); }; export { diff --git a/lib/api.uservoice.js b/lib/api.uservoice.js index 1ae705f..af5ad84 100644 --- a/lib/api.uservoice.js +++ b/lib/api.uservoice.js @@ -15,6 +15,8 @@ import * as RestUtil from './util'; +const HTTP_POST = 'POST'; + /** * Perform a signed redirect request to UserVoice. The result of this method * @@ -23,7 +25,7 @@ import * as RestUtil from './util'; * @param {Object} callback.err An error that occurred, if any */ const redirect = (restCtx, callback) => { - return RestUtil.performRestRequest(restCtx, '/api/uservoice/redirect', 'POST', null, callback); + return RestUtil.performRestRequest(restCtx, '/api/uservoice/redirect', HTTP_POST, null, callback); }; export { redirect }; diff --git a/lib/api.version.js b/lib/api.version.js index 738799c..ad83b9b 100644 --- a/lib/api.version.js +++ b/lib/api.version.js @@ -15,6 +15,8 @@ import * as RestUtil from './util'; +const HTTP_GET = 'GET'; + /** * Get the version information * @@ -23,7 +25,7 @@ import * as RestUtil from './util'; * @param {Object} callback.version The version information */ const getVersion = (restCtx, callback) => { - RestUtil.performRestRequest(restCtx, '/api/version', 'GET', null, callback); + RestUtil.performRestRequest(restCtx, '/api/version', HTTP_GET, null, callback); }; export { getVersion }; diff --git a/lib/model.js b/lib/model.js index 8340c75..ad514f5 100644 --- a/lib/model.js +++ b/lib/model.js @@ -13,6 +13,8 @@ * permissions and limitations under the License. */ +import { defaultTo } from 'ramda'; + /** * REST Context object used to represent a tenant on which a REST request is done, as well as * the user creditentials of the user performing the action. @@ -29,7 +31,7 @@ export const RestContext = function(host, opts) { const that = {}; - opts = opts || {}; + opts = defaultTo({}, opts); that.host = host; that.username = opts.username; diff --git a/lib/util.js b/lib/util.js index e6f0771..a8a7921 100644 --- a/lib/util.js +++ b/lib/util.js @@ -17,7 +17,47 @@ import events from 'events'; import util from 'util'; import { Stream } from 'stream'; import request from 'request'; -import _ from 'underscore'; + +import { + reject, + either, + filter, + lte, + mergeAll, + map, + split, + isEmpty, + toString, + forEach, + forEachObjIndexed, + equals, + isNil, + defaultTo, + not, + is, + and, + or, + compose +} from 'ramda'; + +const HTTP_GET = 'GET'; +const HTTP_POST = 'POST'; +const HTTP_PUT = 'PUT'; +const HTTP_DELETE = 'DELETE'; + +const emptyString = ''; +const isNotEmpty = compose(not, isEmpty); +const isArray = is(Array); +const isFunction = is(Function); +const isDefined = Boolean; +const isNotDefined = compose(not, isDefined); +const isUndefined = equals(undefined); +const isNotUndefined = compose(not, isUndefined); +const isNull = equals(null); +const isNotNull = compose(not, isNull); +const isBoolean = is(Boolean); +const isObject = is(Object); +const differs = compose(not, equals); /** * ### Events @@ -39,9 +79,7 @@ const emitter = new events.EventEmitter(); * @param {String} uriComponent The URL part to encode and make URL safe * @return {String} The encoded URL part. When null was passed in, this will return '' */ -const encodeURI = function(uriComponent) { - return uriComponent === null ? '' : encodeURIComponent(uriComponent); -}; +const encodeURI = uriComponent => (isNull(uriComponent) ? emptyString : encodeURIComponent(uriComponent)); /** * Perform an HTTP request, automatically handling whether or not it should be multipart. @@ -54,8 +92,8 @@ const encodeURI = function(uriComponent) { * @param {Response} callback.response The response object that was returned by the request node module */ const doRequest = (opts, data, callback) => { - data = data || {}; - callback = callback || function() {}; + data = defaultTo({}, data); + callback = defaultTo(function() {}, callback); /*! * Expand values and check if we're uploading a file (a stream value). Since: @@ -68,11 +106,11 @@ const doRequest = (opts, data, callback) => { * from the file stream. */ let hasStream = false; - _.each(data, (value, key) => { - if (_.isArray(value)) { + forEachObjIndexed((value, key) => { + if (isArray(value)) { // For an array, resolve all inner values and reassign it to the data array - value = _.map(value, innerValue => { - if (_.isFunction(innerValue)) { + value = map(innerValue => { + if (isFunction(innerValue)) { innerValue = innerValue(); if (innerValue instanceof Stream) { hasStream = true; @@ -82,10 +120,10 @@ const doRequest = (opts, data, callback) => { } return innerValue; - }); + }, value); data[key] = value; - } else if (_.isFunction(value)) { + } else if (isFunction(value)) { // Invoke any values that are functions in order to resolve the returned value // for the request value = value(); @@ -97,27 +135,27 @@ const doRequest = (opts, data, callback) => { } else if (value instanceof Stream) { hasStream = true; } - }); + }, data); // Sanitize the parameters to not include null / unspecified values - _.each(data, (value, key) => { - if (value === null || value === undefined) { + forEachObjIndexed((value, key) => { + if (either(isNull, isUndefined)(value)) { delete data[key]; - } else if (_.isArray(value)) { + } else if (isArray(value)) { // Filter out unspecified items from the parameter array, and remove it if it is empty - value = _.compact(value); - if (_.isEmpty(value)) { + value = filter(isDefined, value); + if (isEmpty(value)) { delete data[key]; } else { data[key] = value; } } - }); + }, data); - if (!_.isEmpty(data)) { - if (opts.method === 'GET') { + if (isNotEmpty(data)) { + if (equals(opts.method, HTTP_GET)) { opts.qs = data; - } else if (!hasStream && opts.method !== 'GET') { + } else if (and(isNotDefined(hasStream), differs(opts.method, HTTP_GET))) { opts.form = data; } } @@ -131,7 +169,7 @@ const doRequest = (opts, data, callback) => { }); } - if (response.statusCode >= 400) { + if (lte(400, response.statusCode)) { err = { code: response.statusCode, msg: body }; emitter.emit('error', err, body, response); return callback(err); @@ -152,25 +190,25 @@ const doRequest = (opts, data, callback) => { // We append our data in a multi-part way. // That way we can support buffer/streams as well. const form = req.form(); - _.each(data, (value, key) => { + forEachObjIndexed((value, key) => { // If we're sending parts which have the same name, we have to unroll them // before appending them to the form - if (_.isArray(value)) { - _.each(value, innerValue => { + if (isArray(value)) { + forEach(innerValue => { // Stringify Booleans when uploading files - if (_.isBoolean(value)) { - form.append(key, innerValue.toString()); + if (isBoolean(value)) { + form.append(key, toString(innerValue)); } else { form.append(key, innerValue); } - }); + }, value); // Stringify Booleans when uploading files - } else if (_.isBoolean(value)) { - form.append(key, value.toString()); + } else if (isBoolean(value)) { + form.append(key, toString(value)); } else { form.append(key, value); } - }); + }, data); } }; @@ -186,7 +224,7 @@ const doRequest = (opts, data, callback) => { * @param {String|Object} callback.response The response received from the request. If this is JSON, a parsed JSON object will be returned, otherwise the response will be returned as a string * @api private */ -const _performRestRequest = function(...args) { +const _performRestRequest = (...args) => { const [restCtx, url, method, data, callback] = args; emitter.emit('request', restCtx, url, method, data); @@ -202,22 +240,22 @@ const _performRestRequest = function(...args) { headers: {} }; - if (_.isObject(restCtx.additionalHeaders)) { - requestOpts.headers = _.extend(requestOpts.headers, restCtx.additionalHeaders); + if (isObject(restCtx.additionalHeaders)) { + requestOpts.headers = mergeAll([requestOpts.headers, restCtx.additionalHeaders]); } - let referer = restCtx.host + '/'; + let referer = `${restCtx.host}/`; if (restCtx.hostHeader) { // Set the host header so the app server can determine the tenant requestOpts.headers.host = restCtx.hostHeader; // Grab the protocol from the host to create a referer header value - const [protocol] = restCtx.host.split(':'); + const [protocol] = split(':', restCtx.host); referer = util.format('%s://%s/', protocol, restCtx.hostHeader); } // If a referer was explicitly set, we use that - if (restCtx.refererHeader !== null && restCtx.refererHeader !== undefined) { + if (and(isNotNull(restCtx.refererHeader), isNotUndefined(restCtx.refererHeader))) { referer = restCtx.refererHeader; } @@ -234,15 +272,13 @@ const _performRestRequest = function(...args) { */ const fillCookieJar = (restCtx, callback) => { // If no user is specified, there is no point in doing a login request. - if (!restCtx.username) { - return callback(); - } + if (isNotDefined(restCtx.username)) return callback(); // Log the user in _performRestRequest( restCtx, '/api/auth/login', - 'POST', + HTTP_POST, { username: restCtx.username, password: restCtx.userPassword @@ -269,18 +305,14 @@ const fillCookieJar = (restCtx, callback) => { const performRestRequest = (...args) => { const [restCtx, url, method, data, callback] = args; // If we already have a cookieJar, we can perform the request directly - if (restCtx.cookieJar) { - return _performRestRequest(restCtx, url, method, data, callback); - } + if (restCtx.cookieJar) return _performRestRequest(restCtx, url, method, data, callback); // Otherwise we create a new one restCtx.cookieJar = request.jar(); // Fill the new cookie jar fillCookieJar(restCtx, err => { - if (err) { - return callback(err); - } + if (err) return callback(err); return _performRestRequest(restCtx, url, method, data, callback); });