-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathFileStore.ts
More file actions
64 lines (54 loc) · 1.85 KB
/
FileStore.ts
File metadata and controls
64 lines (54 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import fs from 'fs';
import path from 'path'
import IStore from './IStore'
import IFileLocator from './IFileLocator';
import IStoreLogger from './IStoreLogger';
import IStoreWriter from './IStoreWriter';
/**
* A class that allows for messages to be stored in
* a local file system
*
* Note this class implements the IStore interface
* and now also the IFileLocator interface
*/
export default class FileStore implements IStore, IStoreWriter, IFileLocator {
directory: string
logger: IStoreLogger
constructor(_directory: string, _logger: IStoreLogger) {
this.directory = _directory;
this.logger = _logger;
}
public save(id: number, message: string): void {
this.logger.saving(id, message);
// Below is how we might use LogSavedStoreWriter
// But we will not since it breaks OCP !! Because
// the client cannot change the implentation of
// the logger class if we use this approach.
// NOTEL: A solution is in the next exercise (which is
// to use composition instead of inheritance)
// new LogSavingStoreWriter().save(id, message);
var fileFullName = this.getFileInfo(id);
try {
fs.writeFileSync(fileFullName, message)
} catch (err) {
this.logger.errorSaving(id);
}
this.logger.saved(id, message);
// Below is how we might use LogSavedStoreWriter
// We don't use this for the same reasons as mentioned above
// new LogSavedStoreWriter().save(id, message);
}
public read(id: number): string {
this.logger.readingFilestore(id)
var fileFullName = this.getFileInfo(id);
var exists = fs.existsSync(fileFullName);
if(!exists) {
this.logger.didNotFind(id);
return undefined
}
return fs.readFileSync(fileFullName, {encoding: 'ASCII'});
}
public getFileInfo(id: number): string {
return path.join(__dirname, this.directory, `${id}.txt`)
}
}