@openstax/ts-utils 1.15.1 → 1.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,12 +23,12 @@ const subrequestAuthProvider = (initializer) => (configProvider) => {
23
23
  return { headers };
24
24
  };
25
25
  const loadUser = async () => {
26
- const resolvedCookeiName = await cookieName();
27
- const [token] = (0, _1.getAuthTokenOrCookie)(request, resolvedCookeiName);
26
+ const resolvedCookieName = await cookieName();
27
+ const [token] = (0, _1.getAuthTokenOrCookie)(request, resolvedCookieName);
28
28
  if (!token) {
29
29
  return undefined;
30
30
  }
31
- const headers = { cookie: cookie_1.default.serialize(resolvedCookeiName, token) };
31
+ const headers = { cookie: cookie_1.default.serialize(resolvedCookieName, token) };
32
32
  return initializer.fetch((await accountsBase()).replace(/\/+$/, '') + '/api/user', { headers })
33
33
  .then(response => response.json());
34
34
  };
@@ -4,6 +4,7 @@ exports.dynamoUnversionedDocumentStore = void 0;
4
4
  const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
5
5
  const __1 = require("../../..");
6
6
  const config_1 = require("../../../config");
7
+ const errors_1 = require("../../../errors");
7
8
  const guards_1 = require("../../../guards");
8
9
  const dynamoEncoding_1 = require("../dynamoEncoding");
9
10
  const dynamodb = (0, __1.once)(() => new client_dynamodb_1.DynamoDB({ apiVersion: '2012-08-10' }));
@@ -62,7 +63,7 @@ const dynamoUnversionedDocumentStore = (initializer) => () => (configProvider) =
62
63
  var _a;
63
64
  const result = (_a = item.Attributes) === null || _a === void 0 ? void 0 : _a[field]['N'];
64
65
  if (!result) {
65
- throw new Error(`Item with ${key} "${id}" does not exist`);
66
+ throw new errors_1.NotFoundError(`Item with ${key} "${id}" does not exist`);
66
67
  }
67
68
  return parseFloat(result);
68
69
  });
@@ -31,12 +31,13 @@ const fsModule = __importStar(require("fs"));
31
31
  const path_1 = __importDefault(require("path"));
32
32
  const __1 = require("../../..");
33
33
  const config_1 = require("../../../config");
34
+ const errors_1 = require("../../../errors");
34
35
  const guards_1 = require("../../../guards");
35
36
  const fileSystemUnversionedDocumentStore = (initializer) => () => (configProvider) => (_, hashKey) => {
36
37
  const tableName = (0, config_1.resolveConfigValue)(configProvider[initializer.configSpace || 'fileSystem'].tableName);
37
38
  const tablePath = tableName.then((table) => path_1.default.join(initializer.dataDir, table));
38
39
  const { mkdir, readdir, readFile, writeFile } = (0, guards_1.ifDefined)(initializer.fs, fsModule);
39
- const mkTableDir = new Promise((resolve, reject) => tablePath.then((path) => mkdir(path, { recursive: true }, (err) => err ? reject(err) : resolve())));
40
+ const mkTableDir = new Promise((resolve, reject) => tablePath.then((path) => mkdir(path, { recursive: true }, (err) => err && err.code !== 'EEXIST' ? reject(err) : resolve())));
40
41
  const hashFilename = (value) => `${(0, __1.hashValue)(value)}.json`;
41
42
  const filePath = async (filename) => path_1.default.join(await tablePath, filename);
42
43
  const load = async (filename) => {
@@ -101,7 +102,7 @@ const fileSystemUnversionedDocumentStore = (initializer) => () => (configProvide
101
102
  await mkTableDir;
102
103
  const data = await load(filename);
103
104
  if (!data) {
104
- throw new Error(`Item with ${hashKey.toString()} "${id}" does not exist`);
105
+ throw new errors_1.NotFoundError(`Item with ${hashKey.toString()} "${id}" does not exist`);
105
106
  }
106
107
  const newItem = { ...data, ...item };
107
108
  return new Promise((resolve, reject) => {
@@ -3,7 +3,7 @@ import { ConfigProviderForConfig } from '../../../config';
3
3
  import { VersionedDocumentAuthor, VersionedTDocument } from '.';
4
4
  interface Initializer<C> {
5
5
  dataDir: string;
6
- fs?: Pick<typeof import('fs'), 'readFile' | 'writeFile'>;
6
+ fs?: Pick<typeof import('fs'), 'mkdir' | 'readdir' | 'readFile' | 'writeFile'>;
7
7
  configSpace?: C;
8
8
  }
9
9
  export declare const fileSystemVersionedDocumentStore: <C extends string = "fileSystem">(initializer: Initializer<C>) => <T extends VersionedTDocument<T>>() => (configProvider: { [key in C]: {
@@ -1,94 +1,36 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
2
  Object.defineProperty(exports, "__esModule", { value: true });
29
3
  exports.fileSystemVersionedDocumentStore = void 0;
30
- const fsModule = __importStar(require("fs"));
31
- const path_1 = __importDefault(require("path"));
32
- const __1 = require("../../..");
33
- const config_1 = require("../../../config");
34
- const guards_1 = require("../../../guards");
4
+ const file_system_1 = require("../unversioned/file-system");
35
5
  const PAGE_LIMIT = 5;
36
6
  const fileSystemVersionedDocumentStore = (initializer) => () => (configProvider) => (_, hashKey, getAuthor) => {
37
- const tableName = (0, config_1.resolveConfigValue)(configProvider[initializer.configSpace || 'fileSystem'].tableName);
38
- const filePath = tableName.then((table) => path_1.default.join(initializer.dataDir, table));
39
- const { readFile, writeFile } = (0, guards_1.ifDefined)(initializer.fs, fsModule);
40
- let data;
41
- const load = filePath.then(path => new Promise(resolve => {
42
- readFile(path, (err, readData) => {
43
- if (err) {
44
- console.error(err);
45
- }
46
- else {
47
- try {
48
- data = JSON.parse(readData.toString());
49
- if (typeof data !== 'object') {
50
- data = undefined;
51
- }
52
- }
53
- catch (e) {
54
- console.error(e);
55
- }
56
- }
57
- resolve();
58
- });
59
- }));
60
- let previousSave;
7
+ const unversionedDocuments = (0, file_system_1.fileSystemUnversionedDocumentStore)(initializer)()(configProvider)({}, 'id');
61
8
  return {
62
- loadAllDocumentsTheBadWay: async () => {
63
- await load;
64
- return Object.entries(data || []).map(([, versions]) => {
65
- const versionsList = Object.values(versions);
66
- return versionsList[versionsList.length - 1];
67
- });
9
+ loadAllDocumentsTheBadWay: () => {
10
+ return unversionedDocuments.loadAllDocumentsTheBadWay().then(documents => documents.map(document => {
11
+ return document.items[document.items.length - 1];
12
+ }));
68
13
  },
69
14
  getVersions: async (id, startVersion) => {
70
- await load;
71
- const versions = data === null || data === void 0 ? void 0 : data[(0, __1.hashValue)(id)];
72
- const versionsList = versions ? Object.values(versions).reverse() : undefined;
73
- if (!versions || !versionsList) {
15
+ const item = await unversionedDocuments.getItem(id);
16
+ const versions = item === null || item === void 0 ? void 0 : item.items.reverse();
17
+ if (!versions) {
74
18
  return undefined;
75
19
  }
76
- const startIndex = startVersion ? versionsList.indexOf(versions[startVersion.toString()]) + 1 : 0;
77
- const items = versionsList.slice(startIndex, startIndex + PAGE_LIMIT);
78
- const hasMore = (startIndex + 5) < versionsList.length;
20
+ const startIndex = startVersion ? versions.findIndex(version => version.timestamp === startVersion) + 1 : 0;
21
+ const items = versions.slice(startIndex, startIndex + PAGE_LIMIT);
22
+ const hasMore = (startIndex + 5) < versions.length;
79
23
  return {
80
24
  items,
81
25
  nextPageToken: hasMore ? items[items.length - 1].timestamp : undefined
82
26
  };
83
27
  },
84
28
  getItem: async (id, timestamp) => {
85
- await load;
86
- const versions = data === null || data === void 0 ? void 0 : data[(0, __1.hashValue)(id)];
29
+ const item = await unversionedDocuments.getItem(id);
87
30
  if (timestamp) {
88
- return versions === null || versions === void 0 ? void 0 : versions[timestamp];
31
+ return item === null || item === void 0 ? void 0 : item.items.find(version => version.timestamp === timestamp);
89
32
  }
90
- const versionsList = versions ? Object.values(versions) : [];
91
- return versionsList[versionsList.length - 1];
33
+ return item ? item.items[item.items.length - 1] : undefined;
92
34
  },
93
35
  prepareItem: async (item, ...authorArgs) => {
94
36
  // this getAuthor type is terrible
@@ -97,36 +39,23 @@ const fileSystemVersionedDocumentStore = (initializer) => () => (configProvider)
97
39
  return {
98
40
  document: { ...item, timestamp, author },
99
41
  save: async (changes) => {
100
- await load;
101
- await previousSave;
102
- const save = previousSave = new Promise(resolve => (async () => {
103
- const path = await filePath;
104
- data = data || {};
105
- const document = { ...item, ...changes, timestamp, author };
106
- const hash = (0, __1.hashValue)(document[hashKey]);
107
- const versions = data[hash] = data[hash] || {};
108
- versions[document.timestamp] = document;
109
- writeFile(path, JSON.stringify(data, null, 2), () => resolve(document));
110
- })());
111
- return await save;
42
+ var _a;
43
+ const document = { ...item, ...changes, timestamp, author };
44
+ const container = (_a = await unversionedDocuments.getItem(document[hashKey])) !== null && _a !== void 0 ? _a : { id: document[hashKey], items: [] };
45
+ const updated = { ...container, items: [...container.items, document] };
46
+ await unversionedDocuments.putItem(updated);
47
+ return document;
112
48
  }
113
49
  };
114
50
  },
115
51
  putItem: async (item, ...authorArgs) => {
116
- await load;
117
- await previousSave;
118
- const save = previousSave = new Promise(resolve => (async () => {
119
- // this getAuthor type is terrible
120
- const author = getAuthor ? await getAuthor(...authorArgs) : authorArgs[0];
121
- const document = { ...item, timestamp: new Date().getTime(), author };
122
- const hash = (0, __1.hashValue)(document[hashKey]);
123
- const path = await filePath;
124
- data = data || {};
125
- const versions = data[hash] = data[hash] || {};
126
- versions[document.timestamp] = document;
127
- writeFile(path, JSON.stringify(data, null, 2), () => resolve(document));
128
- })());
129
- return await save;
52
+ var _a;
53
+ const author = getAuthor ? await getAuthor(...authorArgs) : authorArgs[0];
54
+ const document = { ...item, timestamp: new Date().getTime(), author };
55
+ const container = (_a = await unversionedDocuments.getItem(document[hashKey])) !== null && _a !== void 0 ? _a : { id: document[hashKey], items: [] };
56
+ const updated = { ...container, items: [...container.items, document] };
57
+ await unversionedDocuments.putItem(updated);
58
+ return document;
130
59
  },
131
60
  };
132
61
  };