Skip to content

Commit

Permalink
fix: close file handle warning (#715)
Browse files Browse the repository at this point in the history
* fix: close fd warning

* adding changeset

* moving fs.close to finally block

* mock .close for test

* fix tests

---------

Co-authored-by: Praveen Gupta <pravgupt@amazon.com>
  • Loading branch information
bombguy and Amplifiyer authored Nov 20, 2023
1 parent 590662a commit 5f336ff
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/fresh-lobsters-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@aws-amplify/platform-core': patch
---

close file handle after reading config
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@ void describe('config controller', () => {
const mockedFsReadFile = mock.method(fs, 'readFile');
const mockedFsWriteFile = mock.method(fs, 'writeFile');
const mockedFsOpen = mock.method(fs, 'open');
const mockedFdClose = mock.fn();

beforeEach(() => {
mockedFsReadFile.mock.resetCalls();
mockedFsWriteFile.mock.resetCalls();
mockedFsOpen.mock.resetCalls();
mockedFdClose.mock.resetCalls();
});

void it('if config has not been cached, read from fs', async () => {
mockedFsOpen.mock.mockImplementationOnce(() => {
return Promise.resolve();
return Promise.resolve({
close: mockedFdClose,
});
});
mockedFsReadFile.mock.mockImplementationOnce(function () {
return Promise.resolve('{"hello": 123}');
Expand All @@ -26,6 +30,7 @@ void describe('config controller', () => {
assert.strictEqual(resolvedValue, undefined);
assert.strictEqual(mockedFsOpen.mock.callCount(), 1);
assert.strictEqual(mockedFsReadFile.mock.callCount(), 1);
assert.strictEqual(mockedFdClose.mock.callCount(), 1);
});

void it('should not throw & return undefined with path points to undefined nested object ', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,22 @@ export class LocalConfigurationController implements ConfigurationController {
if (this._store) {
return this._store;
}
// check if file exists & readable.
let fd;

try {
// check if file exists & readable.
const fd = await fs.open(
fd = await fs.open(
this.configFilePath,
fs.constants.F_OK,
fs.constants.O_RDWR
);

const fileContent = await fs.readFile(fd, 'utf-8');
this._store = JSON.parse(fileContent);
} catch {
this._store = {};
await this.write();
} finally {
await fd?.close();
}
return this._store;
}
Expand Down

0 comments on commit 5f336ff

Please sign in to comment.