Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sdmext279/read document #6

Merged
merged 17 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const config = {
verbose: true,
testTimeout: 100000,
testMatch: ["**/test/**/**/*.test.js"],
testMatch: ["**/test/**/*.test.js"],
collectCoverageFrom: ["**/lib/**/*"],
coveragePathIgnorePatterns: ["node_modules", "<rootDir>/lib/persistence"],
coverageReporters: ["lcov", "text", "text-summary"],
};

module.exports = config;
module.exports = config;
32 changes: 32 additions & 0 deletions lib/handler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,37 @@ const { getConfigurations } = require("../util");
const axios = require("axios").default;
const FormData = require("form-data");

async function readAttachment(Key,token,credentials) {
try {
const document = await readDocument(Key,token,credentials.uri)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add spaces after commas in readAttachment() & readDocument()

return document
} catch (error) {
throw new Error(error);
}
}

async function readDocument(Key, token, uri){
const { repositoryId } = getConfigurations();
const documentReadURL = uri+ "browser/" + repositoryId + "/root?objectID=" + Key + "&cmisselector=content";
const config = {
headers: {Authorization: `Bearer ${token}`},
responseType: 'arraybuffer'
};

try {
const response = await axios.get(documentReadURL, config);
const responseBuffer = Buffer.from(response.data, 'binary');
return responseBuffer;
} catch (error) {
let statusText = "An Error Occurred";
if (error.response && error.response.statusText) {
statusText = error.response.statusText;
}

throw new Error(statusText);
}
}

async function createAttachment(data, credentials, token, attachments) {
const { repositoryId } = getConfigurations();
const documentCreateURL =
Expand Down Expand Up @@ -72,4 +103,5 @@ const updateServerRequest = async (
module.exports = {
createAttachment,
deleteAttachment,
readAttachment,
};
5 changes: 5 additions & 0 deletions lib/persistence/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const cds = require("@sap/cds/lib");
const { SELECT } = cds.ql;

async function getURLFromAttachments(keys, attachments) {
return await SELECT.from(attachments, keys).columns("url");
}

async function getDraftAttachments(attachments, req) {
const up_ = attachments.keys.up_.keys[0].$generatedFieldName;
const idValue = up_.split("__")[1];
Expand All @@ -25,4 +29,5 @@ module.exports = {
getDraftAttachments,
getDuplicateAttachments,
getURLsToDeleteFromAttachments,
getURLFromAttachments
};
19 changes: 18 additions & 1 deletion lib/sdm.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
const cds = require("@sap/cds/lib");
const { createAttachment, deleteAttachment } = require("../lib/handler");
const { createAttachment, deleteAttachment, readAttachment } = require("../lib/handler");
const { fetchAccessToken } = require("./util/index");
const {
getDraftAttachments,
getDuplicateAttachments,
getURLsToDeleteFromAttachments,
getURLFromAttachments
} = require("../lib/persistence");
const { duplicateFileErr } = require("./util/messageConsts");
const { fileNotFoundErr } = require("./util/messageConsts");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this import


module.exports = class SDMAttachmentsService extends (
require("@cap-js/attachments/lib/basic")
Expand All @@ -19,6 +21,21 @@ module.exports = class SDMAttachmentsService extends (
return this.creds;
}

async get(attachments, keys) {
const response = await getURLFromAttachments(keys, attachments);
const token = await fetchAccessToken(this.creds);
try {
if (response?.url) {
const Key = response.url;
const content = await readAttachment(Key, token, this.creds);
return content;
}
throw new Error("Url not found");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we put this message in message constant file

} catch (error) {
throw new Error(fileNotFoundErr());
}
}

async draftSaveHandler(req) {
const attachments =
cds.model.definitions[req.query.target.name + ".attachments"];
Expand Down
2 changes: 2 additions & 0 deletions lib/util/messageConsts.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
module.exports.duplicateFileErr = (duplicateFiles) =>
`The files ${duplicateFiles} are already present in the repository. Please remove them from drafts, rename and try again.`;
module.exports.fileNotFoundErr = (fileNotFound) =>
`File not found.`;
47 changes: 47 additions & 0 deletions test/lib/handler/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,55 @@
const { getConfigurations } = require("../../../lib/util/index");
const createAttachment = require("../../../lib/handler/index").createAttachment;
const deleteAttachment = require("../../../lib/handler/index").deleteAttachment;
const readAttachment = require("../../../lib/handler/index").readAttachment;

describe("handlers", () => {
describe('ReadAttachment function', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('returns document on successful read', async () => {
const mockKey = '123';
const mockToken = 'a1b2c3';
Dismissed Show dismissed Hide dismissed
const mockCredentials = {uri: 'http://example.com/'};
const mockRepositoryId = '123';

const mockResponse = {data: 'mock pdf file content'};
const mockBuffer = Buffer.from(mockResponse.data, 'binary');

axios.get.mockResolvedValue(mockResponse);
getConfigurations.mockReturnValue({repositoryId: mockRepositoryId});

const document = await readAttachment(mockKey, mockToken, mockCredentials);

const expectedUrl = mockCredentials.uri+ "browser/" + mockRepositoryId + "/root?objectID=" + mockKey + "&cmisselector=content";
expect(axios.get).toHaveBeenCalledWith(expectedUrl, {
headers: {Authorization: `Bearer ${mockToken}`},
responseType: 'arraybuffer'
});
expect(document).toEqual(mockBuffer);
});

it('throws error on unsuccessful read', async () => {
axios.get.mockImplementationOnce(() => Promise.reject({
response: {
statusText: 'something bad happened'
}
}));

await expect(readAttachment('123', 'a1b2c3', {uri: 'http://example.com/'})).rejects.toThrow('something bad happened');
Dismissed Show dismissed Hide dismissed
});

it('throws error with "An Error Occurred" message when statusText is missing', async () => {
axios.get.mockImplementationOnce(() => Promise.reject({
response: {}
}));

await expect(readAttachment('123', 'a1b2c3', {uri: 'http://example.com/'})).rejects.toThrow('An Error Occurred');
Dismissed Show dismissed Hide dismissed
});
});

describe("createAttachment function", () => {
beforeEach(() => {
jest.clearAllMocks();
Expand Down
48 changes: 48 additions & 0 deletions test/lib/sdm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,28 @@ const getDuplicateAttachments =
require("../../lib/persistence").getDuplicateAttachments;
const getURLsToDeleteFromAttachments =
require("../../lib/persistence").getURLsToDeleteFromAttachments;
const getURLFromAttachments =
require("../../lib/persistence").getURLFromAttachments;
const fetchAccessToken = require("../../lib/util").fetchAccessToken;
const deleteAttachment = require("../../lib/handler").deleteAttachment;
const createAttachment = require("../../lib/handler").createAttachment;
const readAttachment = require("../../lib/handler").readAttachment;
const { duplicateFileErr } = require("../../lib/util/messageConsts");

jest.mock("@cap-js/attachments/lib/basic", () => class {});
jest.mock("../../lib/persistence", () => ({
getDraftAttachments: jest.fn(),
getDuplicateAttachments: jest.fn(),
getURLsToDeleteFromAttachments: jest.fn(),
getURLFromAttachments: jest.fn()
}));
jest.mock("../../lib/util", () => ({
fetchAccessToken: jest.fn(),
}));
jest.mock("../../lib/handler", () => ({
deleteAttachment: jest.fn(),
createAttachment: jest.fn(),
readAttachment: jest.fn(),
}));
jest.mock("@sap/cds/lib", () => {
const mockCds = {
Expand All @@ -33,6 +38,49 @@ jest.mock("@sap/cds/lib", () => {
});

describe("SDMAttachmentsService", () => {
describe("Test get method", () => {
let service;
beforeEach(() => {
const cds = require("@sap/cds");
service = new SDMAttachmentsService();
service.creds = { uri: "mock_cred" };
});

it("should interact with DB, fetch access token and readAttachment with correct parameters", async () => {
const attachments = ["attachment1", "attachment2"];
const keys = ["key1", "key2"];
const token = "dummy_token";
const response = {url:'mockUrl'}

fetchAccessToken.mockResolvedValueOnce(token);
getURLFromAttachments.mockResolvedValueOnce(response)

await service.get(attachments, keys);

expect(getURLFromAttachments).toHaveBeenCalledWith(keys,attachments)
expect(fetchAccessToken).toHaveBeenCalledWith(service.creds);
expect(readAttachment).toHaveBeenCalledWith("mockUrl", token, service.creds);
});

it("should throw an error if the url is not found", async () => {
const attachments = ["attachment1", "attachment2"];
const keys = ["key1", "key2"];
const token = "dummy_token";

getURLFromAttachments.mockResolvedValueOnce({})
fetchAccessToken.mockResolvedValueOnce(token);

try {
await service.get(attachments, keys);
} catch(e) {
expect(e).toBeInstanceOf(Error);
expect(e).toHaveProperty('message', 'File not found.');
}

expect(getURLFromAttachments).toHaveBeenCalledWith(keys,attachments)
expect(fetchAccessToken).toHaveBeenCalledWith(service.creds);
});
});
describe("draftSaveHandler", () => {
let service;
let mockReq;
Expand Down
Loading