Skip to content

Commit

Permalink
structure change and bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mahajanankur committed Oct 18, 2022
1 parent 18c29d9 commit 0cbf0d9
Show file tree
Hide file tree
Showing 15 changed files with 105 additions and 90 deletions.
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ The access token will expire after 4 hours, so you need to generate a new access
```javascript
(async() => {
try {
const refreshToken = await oauth.getRefreshedToken({
refreshToken: 'changeme',
clientId: 'changeme',
clientSecret: 'changeme'
});
const refreshToken = await oauth.getRefreshedToken();
console.log(refreshToken);
} catch (error) {
console.log(error.message);
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const APIs = require('./src/controllers');
const APIs = require('./src/core');
const validations = require('./src/validations');
const { startClient } = require('./src/controllers/client/start-client');
const { startClient } = require('./src/core/client/start-client');

/**
* @class Searchunify
Expand Down
36 changes: 18 additions & 18 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "su-sdk",
"version": "1.0.3",
"version": "1.0.4",
"description": "SearchUnify javascript SDK enables developers to easily work with the SearchUnify platform and build scalable solutions with search, analytics, crawlers and more.",
"main": "index.js",
"repository": {
Expand Down
File renamed without changes.
37 changes: 22 additions & 15 deletions src/controllers/auth/oauth2.js → src/core/auth/oauth2.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,26 @@ const generateToken = async (params) => {
}
}

let response = await HttpRequest(options);
if (response.status && response.data && response.data.accessToken) {
AUTHENTICATION.OAUTH2.ACCESS_TOKEN = response.data.accessToken;
AUTHENTICATION.OAUTH2.REFRESH_TOKEN = response.data.refreshToken;
let { data, status, message } = await HttpRequest(options);
if (status && data.accessToken) {
AUTHENTICATION.OAUTH2.ACCESS_TOKEN = data.accessToken;
AUTHENTICATION.OAUTH2.REFRESH_TOKEN = data.refreshToken;
AUTHENTICATION.AUTH_TYPE = 'oauth2';
AUTHENTICATION.OAUTH2.CLIENT_ID = isValid.value.clientId;
AUTHENTICATION.OAUTH2.CLIENT_SECRET = isValid.value.clientSecret;
return 'Token generated successfully.';
}
else {
throw new Error(`Client not initilized. Error message (${message})`);
}
return response;
}

const getRefreshedToken = async (params) => {
const isValid = validation.oauth2.refreshTokenValidation(params, validateClient());
if (isValid.error) throw new Error(isValid.error.message);
const getRefreshedToken = async () => {
validateClient();
const queryStrings = qs.stringify({
grant_type: 'refresh_token',
client_id: isValid.value.clientId,
client_secret: isValid.value.clientSecret,
client_id: AUTHENTICATION.OAUTH2.CLIENT_ID,
client_secret: AUTHENTICATION.OAUTH2.CLIENT_SECRET,
refresh_token: AUTHENTICATION.OAUTH2.REFRESH_TOKEN
});

Expand All @@ -55,13 +59,16 @@ const getRefreshedToken = async (params) => {
'Cache-Control': 'no-cache'
}
}
let response = await HttpRequest(options);
if (response.status && response.data && response.data.accessToken) {
AUTHENTICATION.OAUTH2.ACCESS_TOKEN = response.data.accessToken;
AUTHENTICATION.OAUTH2.REFRESH_TOKEN = response.data.refreshToken;
let { data, status, message } = await HttpRequest(options);
if (status && data.accessToken) {
AUTHENTICATION.OAUTH2.ACCESS_TOKEN = data.accessToken;
AUTHENTICATION.OAUTH2.REFRESH_TOKEN = data.refreshToken;
AUTHENTICATION.AUTH_TYPE = 'oauth2';
return 'Token refreshed successfully.';
}
else {
throw new Error(`Token not refreshed. Error message (${message})`);
}
return response;
}

module.exports = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ const { AUTHENTICATION } = require("./../../utils/constants");

exports.startClient = (params) => {
AUTHENTICATION.INSTANCE_URL = params.instance;
AUTHENTICATION.REQUEST_TIMEOUT = params.timeout;
AUTHENTICATION.REQUEST_TIMEOUT = params.timeout ? params.timeout: AUTHENTICATION.REQUEST_TIMEOUT;
}

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const qs = require('qs');
const { CONTENT_API } = require("../../utils/su-apis");
const { AUTHENTICATION } = require("../../utils/constants");
const { HttpRequest } = require("../../utils/request-handler");
Expand Down Expand Up @@ -57,9 +58,14 @@ const getObjectSpecificData = async (params) => {
const isValid = validation.content.objectSpecificDataValidation(params, validateClient(AUTHENTICATION));
if (isValid.error) throw new Error(isValid.error.message);

const queryParams = qs.stringify({
from: isValid.value.offset,
size: isValid.value.size
});

const options = {
method: 'get',
url: `${AUTHENTICATION.INSTANCE_URL}${CONTENT_API.OBJECT_DATA.replace('<contentSourceId>', isValid.value.contentSourceId).replace('<objectId>', isValid.value.objectId)}`,
url: `${AUTHENTICATION.INSTANCE_URL}${CONTENT_API.OBJECT_DATA.replace('<contentSourceId>', isValid.value.contentSourceId).replace('<objectId>', isValid.value.objectId)}?${queryParams}`,
headers: {
'Authorization': getAuthHeader(),
'Content-Type': 'application/json'
Expand All @@ -71,9 +77,8 @@ const getObjectSpecificData = async (params) => {
}

const getObjectSpecificDataWithId = async (params) => {
const isValid = validation.content.objectSpecificDataWithIdValidation(params, validateClient(AUTHENTICATION));
let isValid = validation.content.objectSpecificDataWithIdValidation(params, validateClient(AUTHENTICATION));
if (isValid.error) throw new Error(isValid.error.message);

const options = {
method: 'get',
url: `${AUTHENTICATION.INSTANCE_URL}${CONTENT_API.OBJECT_DATA_WITH_ID.replace('<contentSourceId>', isValid.value.contentSourceId).replace('<objectId>', isValid.value.objectId).replace('<documentId>', isValid.value.documentId)}`,
Expand Down
File renamed without changes.
File renamed without changes.
14 changes: 8 additions & 6 deletions src/utils/constants.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
exports.AUTHENTICATION = {
REQUEST_TIMEOUT: 60000,
INSTANCE_URL: '',
AUTH_TYPE: '',
INSTANCE_URL: null,
AUTH_TYPE: null,
OAUTH2: {
ACCESS_TOKEN: '',
REFRESH_TOKEN: ''
ACCESS_TOKEN: null,
REFRESH_TOKEN: null,
CLIENT_ID: null,
CLIENT_SECRET: null
},
JWT: {
JWT_TOKEN: '',
JWT_TOKEN: null,
},
API_KEY: {
API_KEY_TOKEN: '',
API_KEY_TOKEN: null,
}
}
51 changes: 22 additions & 29 deletions src/utils/request-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,36 @@ const axios = require('axios');
const { Response } = require('./response');
const { AUTHENTICATION } = require('./constants')

const updateResponse = (response) => {
const responseHandler = (response) => {
// delete extra message and statuscode.
let { data, message } = response;
let successMessage = message ? message : `Successfully done.`;
if (message) delete response.message;
let result = {
message: null,
data: null
}
if (response.data && response.data.data) {
result.message = response.data.message;
result.data = response.data.data;
delete response.data.data.message;
delete response.data.data.status;
}
else if (response.data) {
result.message = response.data.message;
result.data = response.data;
delete response.data.message;
delete response.data.status;
status: true,
message: successMessage,
data: data ? data : response
}
return result;
}

exports.HttpRequest = async (options) => {
try {
const requestPayload = {...options, timeout: AUTHENTICATION.REQUEST_TIMEOUT };
let response = await axios(requestPayload);
const result = updateResponse(response);
return new Response(true, result.message, result.data);
const requestPayload = { ...options, timeout: AUTHENTICATION.REQUEST_TIMEOUT };
let { data } = await axios(requestPayload);
const result = responseHandler(data);
return result
} catch (error) {
let message = error.message;
if (error.response && error.response.data) {
if (error.response.data.message) {
message = error.response.data.message;
}
else if (error.response.data.error) {
message = error.response.data.error;
}
let errorMessage = '';
let { response, message } = error;
let { data } = response;
if (data && data.error) {
errorMessage = data.error.message ? data.error.message : message;
}

return new Response(false, message);
else if (data && data.message) {
errorMessage = data.message ? data.message : message;
}

return new Response(false, errorMessage);
}
}
9 changes: 3 additions & 6 deletions src/utils/response.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
/**
* @param status Api response status like true/false.
* @param message Api response message.
* @param data Api response data.
* @summary Successful response format.
* @summary Unsuccessful response format.
*/
exports.Response = function (status, message, data) {
const defaultMessage = 'Successful response.';
exports.Response = function (status, message) {
this.status = status;
this.message = message ? message : defaultMessage;
if (data) this.data = data;
this.message = message;
};
2 changes: 1 addition & 1 deletion src/validations/client/start-client-validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ exports.validateClient = () => {
const schema = Joi.object().keys({
ACCESS_TOKEN: Joi.string().trim().required().error(new Error(`Invalid access token.`)),
REFRESH_TOKEN: Joi.string().trim().required().error(new Error(`Invalid refresh token.`)),
})
}).unknown(true);
const isValid = schema.validate(oauth2);
if (isValid.error) throw new Error(isValid.error.message);
}
Expand Down
21 changes: 18 additions & 3 deletions src/validations/content/content-validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const objectSpecificDataValidation = (options) => {
const schema = Joi.object().keys({
contentSourceId: Joi.string().trim().required(),
objectId: Joi.string().trim().required(),
startFrom: Joi.number(),
offset: Joi.number(),
size: Joi.number().min(1).max(50)
});
const result = schema.validate(options);
Expand All @@ -26,7 +26,10 @@ const objectSpecificDataWithIdValidation = (options) => {
documentId: Joi.string().trim().required()
});
const result = schema.validate(options);
return result;
const response = encodePathUri(result, {
documentId: true // Boolean values: if encode needed.
})
return response;
}


Expand All @@ -38,7 +41,10 @@ const updateDoucmentByIdValidation = (options) => {
data: Joi.object().min(1).required()
});
const result = schema.validate(options);
return result;
const response = encodePathUri(result, {
documentId: true
})
return response;
}

const uploadDataValidation = (options) => {
Expand All @@ -51,6 +57,15 @@ const uploadDataValidation = (options) => {
return result;
}

const encodePathUri = (result, encodeParams) => {
Object.keys(encodeParams).forEach(items => {
if (encodeParams[items] === true) {
result.value[items] = encodeURIComponent(encodeURIComponent(result.value[items]))
}
});
return result;
}

module.exports = {
contentSourceIdValidation,
objectSpecificDataValidation,
Expand Down

0 comments on commit 0cbf0d9

Please sign in to comment.