@better-auth/memory-adapter 1.5.0-beta.9
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.
- package/.turbo/turbo-build.log +13 -0
- package/LICENSE.md +20 -0
- package/dist/index.d.mts +14 -0
- package/dist/index.mjs +213 -0
- package/package.json +37 -0
- package/src/index.ts +5 -0
- package/src/memory-adapter.ts +355 -0
- package/tsconfig.json +9 -0
- package/tsdown.config.ts +7 -0
- package/vitest.config.ts +3 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
|
|
2
|
+
> @better-auth/memory-adapter@1.5.0-beta.9 build /home/runner/work/better-auth/better-auth/packages/memory-adapter
|
|
3
|
+
> tsdown
|
|
4
|
+
|
|
5
|
+
[34mℹ[39m tsdown [2mv0.19.0[22m powered by rolldown [2mv1.0.0-beta.59[22m
|
|
6
|
+
[34mℹ[39m config file: [4m/home/runner/work/better-auth/better-auth/packages/memory-adapter/tsdown.config.ts[24m
|
|
7
|
+
[34mℹ[39m entry: [34msrc/index.ts[39m
|
|
8
|
+
[34mℹ[39m tsconfig: [34mtsconfig.json[39m
|
|
9
|
+
[34mℹ[39m Build start
|
|
10
|
+
[34mℹ[39m [2mdist/[22m[1mindex.mjs[22m [2m8.16 kB[22m [2m│ gzip: 2.21 kB[22m
|
|
11
|
+
[34mℹ[39m [2mdist/[22m[32m[1mindex.d.mts[22m[39m [2m0.63 kB[22m [2m│ gzip: 0.29 kB[22m
|
|
12
|
+
[34mℹ[39m 2 files, total: 8.79 kB
|
|
13
|
+
[32m✔[39m Build complete in [32m7750ms[39m
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright (c) 2024 - present, Bereket Engida
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
5
|
+
this software and associated documentation files (the “Software”), to deal in
|
|
6
|
+
the Software without restriction, including without limitation the rights to
|
|
7
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
8
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
9
|
+
subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
16
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
19
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
20
|
+
DEALINGS IN THE SOFTWARE.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as _better_auth_core_db_adapter0 from "@better-auth/core/db/adapter";
|
|
2
|
+
import { DBAdapterDebugLogOption } from "@better-auth/core/db/adapter";
|
|
3
|
+
import { BetterAuthOptions } from "@better-auth/core";
|
|
4
|
+
|
|
5
|
+
//#region src/memory-adapter.d.ts
|
|
6
|
+
interface MemoryDB {
|
|
7
|
+
[key: string]: any[];
|
|
8
|
+
}
|
|
9
|
+
interface MemoryAdapterConfig {
|
|
10
|
+
debugLogs?: DBAdapterDebugLogOption | undefined;
|
|
11
|
+
}
|
|
12
|
+
declare const memoryAdapter: (db: MemoryDB, config?: MemoryAdapterConfig | undefined) => (options: BetterAuthOptions) => _better_auth_core_db_adapter0.DBAdapter<BetterAuthOptions>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { type MemoryAdapterConfig, type MemoryDB, memoryAdapter };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createAdapterFactory } from "@better-auth/core/db/adapter";
|
|
2
|
+
import { logger } from "@better-auth/core/env";
|
|
3
|
+
|
|
4
|
+
//#region src/memory-adapter.ts
|
|
5
|
+
const memoryAdapter = (db, config) => {
|
|
6
|
+
let lazyOptions = null;
|
|
7
|
+
const adapterCreator = createAdapterFactory({
|
|
8
|
+
config: {
|
|
9
|
+
adapterId: "memory",
|
|
10
|
+
adapterName: "Memory Adapter",
|
|
11
|
+
usePlural: false,
|
|
12
|
+
debugLogs: config?.debugLogs || false,
|
|
13
|
+
supportsArrays: true,
|
|
14
|
+
customTransformInput(props) {
|
|
15
|
+
if ((props.options.advanced?.database?.useNumberId || props.options.advanced?.database?.generateId === "serial") && props.field === "id" && props.action === "create") return db[props.model].length + 1;
|
|
16
|
+
return props.data;
|
|
17
|
+
},
|
|
18
|
+
transaction: async (cb) => {
|
|
19
|
+
const clone = structuredClone(db);
|
|
20
|
+
try {
|
|
21
|
+
return await cb(adapterCreator(lazyOptions));
|
|
22
|
+
} catch (error) {
|
|
23
|
+
Object.keys(db).forEach((key) => {
|
|
24
|
+
db[key] = clone[key];
|
|
25
|
+
});
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
adapter: ({ getFieldName, options, getModelName }) => {
|
|
31
|
+
const applySortToRecords = (records, sortBy, model) => {
|
|
32
|
+
if (!sortBy) return records;
|
|
33
|
+
return records.sort((a, b) => {
|
|
34
|
+
const field = getFieldName({
|
|
35
|
+
model,
|
|
36
|
+
field: sortBy.field
|
|
37
|
+
});
|
|
38
|
+
const aValue = a[field];
|
|
39
|
+
const bValue = b[field];
|
|
40
|
+
let comparison = 0;
|
|
41
|
+
if (aValue == null && bValue == null) comparison = 0;
|
|
42
|
+
else if (aValue == null) comparison = -1;
|
|
43
|
+
else if (bValue == null) comparison = 1;
|
|
44
|
+
else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue);
|
|
45
|
+
else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();
|
|
46
|
+
else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue;
|
|
47
|
+
else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
|
|
48
|
+
else comparison = String(aValue).localeCompare(String(bValue));
|
|
49
|
+
return sortBy.direction === "asc" ? comparison : -comparison;
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
function convertWhereClause(where, model, join) {
|
|
53
|
+
const execute = (where$1, model$1) => {
|
|
54
|
+
const table = db[model$1];
|
|
55
|
+
if (!table) {
|
|
56
|
+
logger.error(`[MemoryAdapter] Model ${model$1} not found in the DB`, Object.keys(db));
|
|
57
|
+
throw new Error(`Model ${model$1} not found`);
|
|
58
|
+
}
|
|
59
|
+
const evalClause = (record, clause) => {
|
|
60
|
+
const { field, value, operator } = clause;
|
|
61
|
+
switch (operator) {
|
|
62
|
+
case "in":
|
|
63
|
+
if (!Array.isArray(value)) throw new Error("Value must be an array");
|
|
64
|
+
return value.includes(record[field]);
|
|
65
|
+
case "not_in":
|
|
66
|
+
if (!Array.isArray(value)) throw new Error("Value must be an array");
|
|
67
|
+
return !value.includes(record[field]);
|
|
68
|
+
case "contains": return record[field].includes(value);
|
|
69
|
+
case "starts_with": return record[field].startsWith(value);
|
|
70
|
+
case "ends_with": return record[field].endsWith(value);
|
|
71
|
+
case "ne": return record[field] !== value;
|
|
72
|
+
case "gt": return value != null && Boolean(record[field] > value);
|
|
73
|
+
case "gte": return value != null && Boolean(record[field] >= value);
|
|
74
|
+
case "lt": return value != null && Boolean(record[field] < value);
|
|
75
|
+
case "lte": return value != null && Boolean(record[field] <= value);
|
|
76
|
+
default: return record[field] === value;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
return table.filter((record) => {
|
|
80
|
+
if (!where$1.length || where$1.length === 0) return true;
|
|
81
|
+
let result = evalClause(record, where$1[0]);
|
|
82
|
+
for (const clause of where$1) {
|
|
83
|
+
const clauseResult = evalClause(record, clause);
|
|
84
|
+
if (clause.connector === "OR") result = result || clauseResult;
|
|
85
|
+
else result = result && clauseResult;
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
if (!join) return execute(where, model);
|
|
91
|
+
const baseRecords = execute(where, model);
|
|
92
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
93
|
+
const seenIds = /* @__PURE__ */ new Map();
|
|
94
|
+
for (const baseRecord of baseRecords) {
|
|
95
|
+
const baseId = String(baseRecord.id);
|
|
96
|
+
if (!grouped.has(baseId)) {
|
|
97
|
+
const nested = { ...baseRecord };
|
|
98
|
+
for (const [joinModel, joinAttr] of Object.entries(join)) {
|
|
99
|
+
const joinModelName = getModelName(joinModel);
|
|
100
|
+
if (joinAttr.relation === "one-to-one") nested[joinModelName] = null;
|
|
101
|
+
else {
|
|
102
|
+
nested[joinModelName] = [];
|
|
103
|
+
seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
grouped.set(baseId, nested);
|
|
107
|
+
}
|
|
108
|
+
const nestedEntry = grouped.get(baseId);
|
|
109
|
+
for (const [joinModel, joinAttr] of Object.entries(join)) {
|
|
110
|
+
const joinModelName = getModelName(joinModel);
|
|
111
|
+
const joinTable = db[joinModelName];
|
|
112
|
+
if (!joinTable) {
|
|
113
|
+
logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db));
|
|
114
|
+
throw new Error(`JoinOption model ${joinModelName} not found`);
|
|
115
|
+
}
|
|
116
|
+
const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);
|
|
117
|
+
if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null;
|
|
118
|
+
else {
|
|
119
|
+
const seenSet = seenIds.get(`${baseId}-${joinModel}`);
|
|
120
|
+
const limit = joinAttr.limit ?? 100;
|
|
121
|
+
let count = 0;
|
|
122
|
+
for (const matchingRecord of matchingRecords) {
|
|
123
|
+
if (count >= limit) break;
|
|
124
|
+
if (!seenSet.has(matchingRecord.id)) {
|
|
125
|
+
nestedEntry[joinModelName].push(matchingRecord);
|
|
126
|
+
seenSet.add(matchingRecord.id);
|
|
127
|
+
count++;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return Array.from(grouped.values());
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
create: async ({ model, data }) => {
|
|
137
|
+
if (options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial") data.id = db[getModelName(model)].length + 1;
|
|
138
|
+
if (!db[model]) db[model] = [];
|
|
139
|
+
db[model].push(data);
|
|
140
|
+
return data;
|
|
141
|
+
},
|
|
142
|
+
findOne: async ({ model, where, join }) => {
|
|
143
|
+
const res = convertWhereClause(where, model, join);
|
|
144
|
+
if (join) {
|
|
145
|
+
const resArray = res;
|
|
146
|
+
if (!resArray.length) return null;
|
|
147
|
+
return resArray[0];
|
|
148
|
+
}
|
|
149
|
+
return res[0] || null;
|
|
150
|
+
},
|
|
151
|
+
findMany: async ({ model, where, sortBy, limit, offset, join }) => {
|
|
152
|
+
const res = convertWhereClause(where || [], model, join);
|
|
153
|
+
if (join) {
|
|
154
|
+
const resArray = res;
|
|
155
|
+
if (!resArray.length) return [];
|
|
156
|
+
applySortToRecords(resArray, sortBy, model);
|
|
157
|
+
let paginatedRecords = resArray;
|
|
158
|
+
if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);
|
|
159
|
+
if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);
|
|
160
|
+
return paginatedRecords;
|
|
161
|
+
}
|
|
162
|
+
let table = applySortToRecords(res, sortBy, model);
|
|
163
|
+
if (offset !== void 0) table = table.slice(offset);
|
|
164
|
+
if (limit !== void 0) table = table.slice(0, limit);
|
|
165
|
+
return table || [];
|
|
166
|
+
},
|
|
167
|
+
count: async ({ model, where }) => {
|
|
168
|
+
if (where) return convertWhereClause(where, model).length;
|
|
169
|
+
return db[model].length;
|
|
170
|
+
},
|
|
171
|
+
update: async ({ model, where, update }) => {
|
|
172
|
+
const res = convertWhereClause(where, model);
|
|
173
|
+
res.forEach((record) => {
|
|
174
|
+
Object.assign(record, update);
|
|
175
|
+
});
|
|
176
|
+
return res[0] || null;
|
|
177
|
+
},
|
|
178
|
+
delete: async ({ model, where }) => {
|
|
179
|
+
const table = db[model];
|
|
180
|
+
const res = convertWhereClause(where, model);
|
|
181
|
+
db[model] = table.filter((record) => !res.includes(record));
|
|
182
|
+
},
|
|
183
|
+
deleteMany: async ({ model, where }) => {
|
|
184
|
+
const table = db[model];
|
|
185
|
+
const res = convertWhereClause(where, model);
|
|
186
|
+
let count = 0;
|
|
187
|
+
db[model] = table.filter((record) => {
|
|
188
|
+
if (res.includes(record)) {
|
|
189
|
+
count++;
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
return !res.includes(record);
|
|
193
|
+
});
|
|
194
|
+
return count;
|
|
195
|
+
},
|
|
196
|
+
updateMany({ model, where, update }) {
|
|
197
|
+
const res = convertWhereClause(where, model);
|
|
198
|
+
res.forEach((record) => {
|
|
199
|
+
Object.assign(record, update);
|
|
200
|
+
});
|
|
201
|
+
return res[0] || null;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
return (options) => {
|
|
207
|
+
lazyOptions = options;
|
|
208
|
+
return adapterCreator(options);
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
//#endregion
|
|
213
|
+
export { memoryAdapter };
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@better-auth/memory-adapter",
|
|
3
|
+
"version": "1.5.0-beta.9",
|
|
4
|
+
"description": "Memory adapter for Better Auth",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/better-auth/better-auth.git",
|
|
9
|
+
"directory": "packages/memory-adapter"
|
|
10
|
+
},
|
|
11
|
+
"main": "./dist/index.mjs",
|
|
12
|
+
"module": "./dist/index.mjs",
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"dev-source": "./src/index.ts",
|
|
17
|
+
"types": "./dist/index.d.mts",
|
|
18
|
+
"default": "./dist/index.mjs"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@better-auth/utils": "^0.3.0",
|
|
23
|
+
"@better-auth/core": "1.5.0-beta.9"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@better-auth/utils": "^0.3.0",
|
|
27
|
+
"tsdown": "^0.19.0",
|
|
28
|
+
"typescript": "^5.9.3",
|
|
29
|
+
"@better-auth/core": "1.5.0-beta.9"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsdown",
|
|
33
|
+
"dev": "tsdown --watch",
|
|
34
|
+
"test": "vitest",
|
|
35
|
+
"typecheck": "tsc --noEmit"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import type { BetterAuthOptions } from "@better-auth/core";
|
|
2
|
+
import type {
|
|
3
|
+
CleanedWhere,
|
|
4
|
+
DBAdapterDebugLogOption,
|
|
5
|
+
JoinConfig,
|
|
6
|
+
} from "@better-auth/core/db/adapter";
|
|
7
|
+
import { createAdapterFactory } from "@better-auth/core/db/adapter";
|
|
8
|
+
import { logger } from "@better-auth/core/env";
|
|
9
|
+
|
|
10
|
+
export interface MemoryDB {
|
|
11
|
+
[key: string]: any[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface MemoryAdapterConfig {
|
|
15
|
+
debugLogs?: DBAdapterDebugLogOption | undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const memoryAdapter = (
|
|
19
|
+
db: MemoryDB,
|
|
20
|
+
config?: MemoryAdapterConfig | undefined,
|
|
21
|
+
) => {
|
|
22
|
+
let lazyOptions: BetterAuthOptions | null = null;
|
|
23
|
+
const adapterCreator = createAdapterFactory({
|
|
24
|
+
config: {
|
|
25
|
+
adapterId: "memory",
|
|
26
|
+
adapterName: "Memory Adapter",
|
|
27
|
+
usePlural: false,
|
|
28
|
+
debugLogs: config?.debugLogs || false,
|
|
29
|
+
supportsArrays: true,
|
|
30
|
+
customTransformInput(props) {
|
|
31
|
+
const useNumberId =
|
|
32
|
+
props.options.advanced?.database?.useNumberId ||
|
|
33
|
+
props.options.advanced?.database?.generateId === "serial";
|
|
34
|
+
if (useNumberId && props.field === "id" && props.action === "create") {
|
|
35
|
+
return db[props.model]!.length + 1;
|
|
36
|
+
}
|
|
37
|
+
return props.data;
|
|
38
|
+
},
|
|
39
|
+
transaction: async (cb) => {
|
|
40
|
+
const clone = structuredClone(db);
|
|
41
|
+
try {
|
|
42
|
+
const r = await cb(adapterCreator(lazyOptions!));
|
|
43
|
+
return r;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
// Rollback changes
|
|
46
|
+
Object.keys(db).forEach((key) => {
|
|
47
|
+
db[key] = clone[key]!;
|
|
48
|
+
});
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
adapter: ({ getFieldName, options, getModelName }) => {
|
|
54
|
+
const applySortToRecords = (
|
|
55
|
+
records: any[],
|
|
56
|
+
sortBy: { field: string; direction: "asc" | "desc" } | undefined,
|
|
57
|
+
model: string,
|
|
58
|
+
) => {
|
|
59
|
+
if (!sortBy) return records;
|
|
60
|
+
return records.sort((a: any, b: any) => {
|
|
61
|
+
const field = getFieldName({ model, field: sortBy.field });
|
|
62
|
+
const aValue = a[field];
|
|
63
|
+
const bValue = b[field];
|
|
64
|
+
|
|
65
|
+
let comparison = 0;
|
|
66
|
+
|
|
67
|
+
// Handle null/undefined values
|
|
68
|
+
if (aValue == null && bValue == null) {
|
|
69
|
+
comparison = 0;
|
|
70
|
+
} else if (aValue == null) {
|
|
71
|
+
comparison = -1;
|
|
72
|
+
} else if (bValue == null) {
|
|
73
|
+
comparison = 1;
|
|
74
|
+
}
|
|
75
|
+
// Handle string comparison
|
|
76
|
+
else if (typeof aValue === "string" && typeof bValue === "string") {
|
|
77
|
+
comparison = aValue.localeCompare(bValue);
|
|
78
|
+
}
|
|
79
|
+
// Handle date comparison
|
|
80
|
+
else if (aValue instanceof Date && bValue instanceof Date) {
|
|
81
|
+
comparison = aValue.getTime() - bValue.getTime();
|
|
82
|
+
}
|
|
83
|
+
// Handle numeric comparison
|
|
84
|
+
else if (typeof aValue === "number" && typeof bValue === "number") {
|
|
85
|
+
comparison = aValue - bValue;
|
|
86
|
+
}
|
|
87
|
+
// Handle boolean comparison
|
|
88
|
+
else if (typeof aValue === "boolean" && typeof bValue === "boolean") {
|
|
89
|
+
comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
|
|
90
|
+
}
|
|
91
|
+
// Fallback to string comparison
|
|
92
|
+
else {
|
|
93
|
+
comparison = String(aValue).localeCompare(String(bValue));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return sortBy.direction === "asc" ? comparison : -comparison;
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
function convertWhereClause(
|
|
101
|
+
where: CleanedWhere[],
|
|
102
|
+
model: string,
|
|
103
|
+
join?: JoinConfig,
|
|
104
|
+
): any[] {
|
|
105
|
+
const execute = (where: CleanedWhere[], model: string) => {
|
|
106
|
+
const table = db[model];
|
|
107
|
+
if (!table) {
|
|
108
|
+
logger.error(
|
|
109
|
+
`[MemoryAdapter] Model ${model} not found in the DB`,
|
|
110
|
+
Object.keys(db),
|
|
111
|
+
);
|
|
112
|
+
throw new Error(`Model ${model} not found`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const evalClause = (record: any, clause: CleanedWhere): boolean => {
|
|
116
|
+
const { field, value, operator } = clause;
|
|
117
|
+
switch (operator) {
|
|
118
|
+
case "in":
|
|
119
|
+
if (!Array.isArray(value)) {
|
|
120
|
+
throw new Error("Value must be an array");
|
|
121
|
+
}
|
|
122
|
+
// @ts-expect-error
|
|
123
|
+
return value.includes(record[field]);
|
|
124
|
+
case "not_in":
|
|
125
|
+
if (!Array.isArray(value)) {
|
|
126
|
+
throw new Error("Value must be an array");
|
|
127
|
+
}
|
|
128
|
+
// @ts-expect-error
|
|
129
|
+
return !value.includes(record[field]);
|
|
130
|
+
case "contains":
|
|
131
|
+
return record[field].includes(value);
|
|
132
|
+
case "starts_with":
|
|
133
|
+
return record[field].startsWith(value);
|
|
134
|
+
case "ends_with":
|
|
135
|
+
return record[field].endsWith(value);
|
|
136
|
+
case "ne":
|
|
137
|
+
return record[field] !== value;
|
|
138
|
+
case "gt":
|
|
139
|
+
return value != null && Boolean(record[field] > value);
|
|
140
|
+
case "gte":
|
|
141
|
+
return value != null && Boolean(record[field] >= value);
|
|
142
|
+
case "lt":
|
|
143
|
+
return value != null && Boolean(record[field] < value);
|
|
144
|
+
case "lte":
|
|
145
|
+
return value != null && Boolean(record[field] <= value);
|
|
146
|
+
default:
|
|
147
|
+
return record[field] === value;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
return table.filter((record: any) => {
|
|
152
|
+
if (!where.length || where.length === 0) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
let result = evalClause(record, where[0]!);
|
|
157
|
+
for (const clause of where) {
|
|
158
|
+
const clauseResult = evalClause(record, clause);
|
|
159
|
+
|
|
160
|
+
if (clause.connector === "OR") {
|
|
161
|
+
result = result || clauseResult;
|
|
162
|
+
} else {
|
|
163
|
+
result = result && clauseResult;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return result;
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
if (!join) return execute(where, model);
|
|
172
|
+
|
|
173
|
+
const baseRecords = execute(where, model);
|
|
174
|
+
|
|
175
|
+
// Group results by base model and nest joined data as arrays
|
|
176
|
+
const grouped = new Map<string, any>();
|
|
177
|
+
// Track seen IDs per joined model for O(1) deduplication
|
|
178
|
+
const seenIds = new Map<string, Set<string>>();
|
|
179
|
+
|
|
180
|
+
for (const baseRecord of baseRecords) {
|
|
181
|
+
const baseId = String(baseRecord.id);
|
|
182
|
+
|
|
183
|
+
if (!grouped.has(baseId)) {
|
|
184
|
+
const nested: Record<string, any> = { ...baseRecord };
|
|
185
|
+
|
|
186
|
+
// Initialize joined data structures based on isUnique
|
|
187
|
+
for (const [joinModel, joinAttr] of Object.entries(join)) {
|
|
188
|
+
const joinModelName = getModelName(joinModel);
|
|
189
|
+
if (joinAttr.relation === "one-to-one") {
|
|
190
|
+
nested[joinModelName] = null;
|
|
191
|
+
} else {
|
|
192
|
+
nested[joinModelName] = [];
|
|
193
|
+
seenIds.set(`${baseId}-${joinModel}`, new Set());
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
grouped.set(baseId, nested);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const nestedEntry = grouped.get(baseId)!;
|
|
201
|
+
|
|
202
|
+
// Add joined data
|
|
203
|
+
for (const [joinModel, joinAttr] of Object.entries(join)) {
|
|
204
|
+
const joinModelName = getModelName(joinModel);
|
|
205
|
+
const joinTable = db[joinModelName];
|
|
206
|
+
if (!joinTable) {
|
|
207
|
+
logger.error(
|
|
208
|
+
`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`,
|
|
209
|
+
Object.keys(db),
|
|
210
|
+
);
|
|
211
|
+
throw new Error(`JoinOption model ${joinModelName} not found`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const matchingRecords = joinTable.filter(
|
|
215
|
+
(joinRecord: any) =>
|
|
216
|
+
joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from],
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
if (joinAttr.relation === "one-to-one") {
|
|
220
|
+
// For unique relationships, store a single object (or null)
|
|
221
|
+
nestedEntry[joinModelName] = matchingRecords[0] || null;
|
|
222
|
+
} else {
|
|
223
|
+
// For non-unique relationships, store array with limit
|
|
224
|
+
const seenSet = seenIds.get(`${baseId}-${joinModel}`)!;
|
|
225
|
+
const limit = joinAttr.limit ?? 100;
|
|
226
|
+
let count = 0;
|
|
227
|
+
|
|
228
|
+
for (const matchingRecord of matchingRecords) {
|
|
229
|
+
if (count >= limit) break;
|
|
230
|
+
if (!seenSet.has(matchingRecord.id)) {
|
|
231
|
+
nestedEntry[joinModelName].push(matchingRecord);
|
|
232
|
+
seenSet.add(matchingRecord.id);
|
|
233
|
+
count++;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return Array.from(grouped.values());
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
create: async ({ model, data }) => {
|
|
244
|
+
const useNumberId =
|
|
245
|
+
options.advanced?.database?.useNumberId ||
|
|
246
|
+
options.advanced?.database?.generateId === "serial";
|
|
247
|
+
if (useNumberId) {
|
|
248
|
+
// @ts-expect-error
|
|
249
|
+
data.id = db[getModelName(model)]!.length + 1;
|
|
250
|
+
}
|
|
251
|
+
if (!db[model]) {
|
|
252
|
+
db[model] = [];
|
|
253
|
+
}
|
|
254
|
+
db[model]!.push(data);
|
|
255
|
+
return data;
|
|
256
|
+
},
|
|
257
|
+
findOne: async ({ model, where, join }) => {
|
|
258
|
+
const res = convertWhereClause(where, model, join);
|
|
259
|
+
if (join) {
|
|
260
|
+
// When join is present, res is an array of nested objects
|
|
261
|
+
const resArray = res as any[];
|
|
262
|
+
if (!resArray.length) {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
// Return the first nested object
|
|
266
|
+
return resArray[0];
|
|
267
|
+
}
|
|
268
|
+
// Without join, res is an array
|
|
269
|
+
const resArray = res as any[];
|
|
270
|
+
const record = resArray[0] || null;
|
|
271
|
+
return record;
|
|
272
|
+
},
|
|
273
|
+
findMany: async ({ model, where, sortBy, limit, offset, join }) => {
|
|
274
|
+
const res = convertWhereClause(where || [], model, join);
|
|
275
|
+
|
|
276
|
+
if (join) {
|
|
277
|
+
// When join is present, res is an array of nested objects
|
|
278
|
+
const resArray = res as any[];
|
|
279
|
+
if (!resArray.length) {
|
|
280
|
+
return [];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Apply sorting to nested objects
|
|
284
|
+
applySortToRecords(resArray, sortBy, model);
|
|
285
|
+
|
|
286
|
+
// Apply offset and limit
|
|
287
|
+
let paginatedRecords = resArray;
|
|
288
|
+
if (offset !== undefined) {
|
|
289
|
+
paginatedRecords = paginatedRecords.slice(offset);
|
|
290
|
+
}
|
|
291
|
+
if (limit !== undefined) {
|
|
292
|
+
paginatedRecords = paginatedRecords.slice(0, limit);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return paginatedRecords;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Without join - original logic
|
|
299
|
+
const resArray = res as any[];
|
|
300
|
+
let table = applySortToRecords(resArray, sortBy, model);
|
|
301
|
+
if (offset !== undefined) {
|
|
302
|
+
table = table!.slice(offset);
|
|
303
|
+
}
|
|
304
|
+
if (limit !== undefined) {
|
|
305
|
+
table = table!.slice(0, limit);
|
|
306
|
+
}
|
|
307
|
+
return table || [];
|
|
308
|
+
},
|
|
309
|
+
count: async ({ model, where }) => {
|
|
310
|
+
if (where) {
|
|
311
|
+
const filteredRecords = convertWhereClause(where, model);
|
|
312
|
+
return filteredRecords.length;
|
|
313
|
+
}
|
|
314
|
+
return db[model]!.length;
|
|
315
|
+
},
|
|
316
|
+
update: async ({ model, where, update }) => {
|
|
317
|
+
const res = convertWhereClause(where, model);
|
|
318
|
+
res.forEach((record) => {
|
|
319
|
+
Object.assign(record, update);
|
|
320
|
+
});
|
|
321
|
+
return res[0] || null;
|
|
322
|
+
},
|
|
323
|
+
delete: async ({ model, where }) => {
|
|
324
|
+
const table = db[model]!;
|
|
325
|
+
const res = convertWhereClause(where, model);
|
|
326
|
+
db[model] = table.filter((record) => !res.includes(record));
|
|
327
|
+
},
|
|
328
|
+
deleteMany: async ({ model, where }) => {
|
|
329
|
+
const table = db[model]!;
|
|
330
|
+
const res = convertWhereClause(where, model);
|
|
331
|
+
let count = 0;
|
|
332
|
+
db[model] = table.filter((record) => {
|
|
333
|
+
if (res.includes(record)) {
|
|
334
|
+
count++;
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
return !res.includes(record);
|
|
338
|
+
});
|
|
339
|
+
return count;
|
|
340
|
+
},
|
|
341
|
+
updateMany({ model, where, update }) {
|
|
342
|
+
const res = convertWhereClause(where, model);
|
|
343
|
+
res.forEach((record) => {
|
|
344
|
+
Object.assign(record, update);
|
|
345
|
+
});
|
|
346
|
+
return res[0] || null;
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
},
|
|
350
|
+
});
|
|
351
|
+
return (options: BetterAuthOptions) => {
|
|
352
|
+
lazyOptions = options;
|
|
353
|
+
return adapterCreator(options);
|
|
354
|
+
};
|
|
355
|
+
};
|
package/tsconfig.json
ADDED
package/tsdown.config.ts
ADDED
package/vitest.config.ts
ADDED