fix(DockerContainer): Fix getContainerById to return undefined for non-existent containers
This commit is contained in:
@@ -1,5 +1,52 @@
|
||||
# Docker Module - Development Hints
|
||||
|
||||
## getContainerById() Bug Fix (2025-11-24 - v5.0.1)
|
||||
|
||||
### Problem
|
||||
The `getContainerById()` method had a critical bug where it would create a DockerContainer object from Docker API error responses when a container didn't exist.
|
||||
|
||||
**Symptoms:**
|
||||
- Calling `docker.getContainerById('invalid-id')` returned a DockerContainer object with `{ message: "No such container: invalid-id" }`
|
||||
- Calling `.logs()` on this invalid container returned "[object Object]" instead of logs or throwing an error
|
||||
- No way to detect the error state without checking for a `.message` property
|
||||
|
||||
**Root Cause:**
|
||||
The `DockerContainer._fromId()` method made a direct API call to `/containers/{id}/json` and blindly passed `response.body` to the constructor, even when the API returned a 404 error response.
|
||||
|
||||
### Solution
|
||||
Changed `DockerContainer._fromId()` to use the **list+filter pattern**, matching the behavior of all other resource getter methods (DockerImage, DockerNetwork, DockerService, DockerSecret):
|
||||
|
||||
```typescript
|
||||
// Before (buggy):
|
||||
public static async _fromId(dockerHostArg: DockerHost, containerId: string): Promise<DockerContainer> {
|
||||
const response = await dockerHostArg.request('GET', `/containers/${containerId}/json`);
|
||||
return new DockerContainer(dockerHostArg, response.body); // Creates invalid object from error!
|
||||
}
|
||||
|
||||
// After (fixed):
|
||||
public static async _fromId(dockerHostArg: DockerHost, containerId: string): Promise<DockerContainer | undefined> {
|
||||
const containers = await this._list(dockerHostArg);
|
||||
return containers.find((container) => container.Id === containerId); // Returns undefined if not found
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- 100% consistent with all other resource classes
|
||||
- Type-safe return signature: `Promise<DockerContainer | undefined>`
|
||||
- Cannot create invalid objects - `.find()` naturally returns undefined
|
||||
- Users can now properly check for non-existent containers
|
||||
|
||||
**Usage:**
|
||||
```typescript
|
||||
const container = await docker.getContainerById('abc123');
|
||||
if (container) {
|
||||
const logs = await container.logs();
|
||||
console.log(logs);
|
||||
} else {
|
||||
console.log('Container not found');
|
||||
}
|
||||
```
|
||||
|
||||
## OOP Refactoring - Clean Architecture (2025-11-24)
|
||||
|
||||
### Architecture Changes
|
||||
|
||||
Reference in New Issue
Block a user