@terreno/api 0.0.18 → 0.2.0

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.
Files changed (71) hide show
  1. package/README.md +73 -3
  2. package/dist/api.d.ts +96 -3
  3. package/dist/api.js +159 -11
  4. package/dist/api.test.js +906 -2
  5. package/dist/auth.js +3 -1
  6. package/dist/betterAuth.d.ts +91 -0
  7. package/dist/betterAuth.js +8 -0
  8. package/dist/betterAuth.test.d.ts +1 -0
  9. package/dist/betterAuth.test.js +181 -0
  10. package/dist/betterAuthApp.d.ts +22 -0
  11. package/dist/betterAuthApp.js +38 -0
  12. package/dist/betterAuthApp.test.d.ts +1 -0
  13. package/dist/betterAuthApp.test.js +242 -0
  14. package/dist/betterAuthSetup.d.ts +60 -0
  15. package/dist/betterAuthSetup.js +278 -0
  16. package/dist/betterAuthSetup.test.d.ts +1 -0
  17. package/dist/betterAuthSetup.test.js +684 -0
  18. package/dist/errors.js +14 -11
  19. package/dist/example.js +7 -7
  20. package/dist/expressServer.js +2 -2
  21. package/dist/githubAuth.test.js +3 -3
  22. package/dist/index.d.ts +6 -0
  23. package/dist/index.js +6 -0
  24. package/dist/openApi.test.js +8 -5
  25. package/dist/openApiBuilder.d.ts +69 -1
  26. package/dist/openApiBuilder.js +109 -5
  27. package/dist/openApiValidator.d.ts +296 -0
  28. package/dist/openApiValidator.js +698 -0
  29. package/dist/openApiValidator.test.d.ts +1 -0
  30. package/dist/openApiValidator.test.js +346 -0
  31. package/dist/plugins.test.js +3 -3
  32. package/dist/terrenoApp.d.ts +189 -0
  33. package/dist/terrenoApp.js +352 -0
  34. package/dist/terrenoApp.test.d.ts +1 -0
  35. package/dist/terrenoApp.test.js +264 -0
  36. package/dist/terrenoPlugin.d.ts +38 -0
  37. package/dist/terrenoPlugin.js +2 -0
  38. package/dist/tests.js +34 -24
  39. package/package.json +8 -2
  40. package/src/__snapshots__/openApi.test.ts.snap +399 -0
  41. package/src/__snapshots__/openApiBuilder.test.ts.snap +108 -0
  42. package/src/api.test.ts +743 -2
  43. package/src/api.ts +270 -6
  44. package/src/auth.ts +3 -1
  45. package/src/betterAuth.test.ts +160 -0
  46. package/src/betterAuth.ts +104 -0
  47. package/src/betterAuthApp.test.ts +114 -0
  48. package/src/betterAuthApp.ts +60 -0
  49. package/src/betterAuthSetup.test.ts +485 -0
  50. package/src/betterAuthSetup.ts +251 -0
  51. package/src/errors.ts +14 -11
  52. package/src/example.ts +7 -7
  53. package/src/expressServer.ts +4 -5
  54. package/src/githubAuth.test.ts +3 -3
  55. package/src/index.ts +6 -0
  56. package/src/openApi.test.ts +8 -5
  57. package/src/openApiBuilder.ts +188 -15
  58. package/src/openApiValidator.test.ts +241 -0
  59. package/src/openApiValidator.ts +860 -0
  60. package/src/plugins.test.ts +3 -3
  61. package/src/terrenoApp.test.ts +201 -0
  62. package/src/terrenoApp.ts +347 -0
  63. package/src/terrenoPlugin.ts +39 -0
  64. package/src/tests.ts +34 -24
  65. package/.cursorrules +0 -107
  66. package/.windsurfrules +0 -107
  67. package/AGENTS.md +0 -313
  68. package/dist/response.d.ts +0 -0
  69. package/dist/response.js +0 -1
  70. package/index.ts +0 -1
  71. package/src/response.ts +0 -0
package/src/api.test.ts CHANGED
@@ -858,8 +858,12 @@ describe("@terreno/api", () => {
858
858
  const mongoose = await import("mongoose");
859
859
 
860
860
  const softDeleteSchema = new mongoose.Schema({
861
- deleted: {default: false, type: Boolean},
862
- name: String,
861
+ deleted: {
862
+ default: false,
863
+ description: "Whether this item has been soft deleted",
864
+ type: Boolean,
865
+ },
866
+ name: {description: "The name of the item", type: String},
863
867
  });
864
868
 
865
869
  let SoftDeleteModel;
@@ -1062,6 +1066,743 @@ describe("@terreno/api", () => {
1062
1066
  });
1063
1067
  });
1064
1068
 
1069
+ describe("array operation with undefined preUpdate return", () => {
1070
+ let admin: any;
1071
+ let apple: Food;
1072
+ let agent: TestAgent;
1073
+
1074
+ beforeEach(async () => {
1075
+ [admin] = await setupDb();
1076
+
1077
+ apple = await FoodModel.create({
1078
+ calories: 100,
1079
+ categories: [
1080
+ {name: "Fruit", show: true},
1081
+ {name: "Popular", show: false},
1082
+ ],
1083
+ created: new Date("2021-12-03T00:00:30.000Z"),
1084
+ hidden: false,
1085
+ name: "Apple",
1086
+ ownerId: admin._id,
1087
+ tags: ["healthy", "cheap"],
1088
+ });
1089
+
1090
+ app = getBaseServer();
1091
+ setupAuth(app, UserModel as any);
1092
+ addAuthRoutes(app, UserModel as any);
1093
+ });
1094
+
1095
+ it("array operation preUpdate returning undefined for array POST throws error", async () => {
1096
+ app.use(
1097
+ "/food",
1098
+ modelRouter(FoodModel, {
1099
+ allowAnonymous: true,
1100
+ permissions: {
1101
+ create: [Permissions.IsAdmin],
1102
+ delete: [Permissions.IsAdmin],
1103
+ list: [Permissions.IsAdmin],
1104
+ read: [Permissions.IsAdmin],
1105
+ update: [Permissions.IsAdmin],
1106
+ },
1107
+ preUpdate: () => undefined as any,
1108
+ })
1109
+ );
1110
+ server = supertest(app);
1111
+ agent = await authAsUser(app, "admin");
1112
+
1113
+ const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(403);
1114
+ expect(res.body.title).toBe("Update not allowed");
1115
+ expect(res.body.detail).toBe("A body must be returned from preUpdate");
1116
+ });
1117
+
1118
+ it("array operation preUpdate returning null for array PATCH throws error", async () => {
1119
+ app.use(
1120
+ "/food",
1121
+ modelRouter(FoodModel, {
1122
+ allowAnonymous: true,
1123
+ permissions: {
1124
+ create: [Permissions.IsAdmin],
1125
+ delete: [Permissions.IsAdmin],
1126
+ list: [Permissions.IsAdmin],
1127
+ read: [Permissions.IsAdmin],
1128
+ update: [Permissions.IsAdmin],
1129
+ },
1130
+ preUpdate: () => null,
1131
+ })
1132
+ );
1133
+ server = supertest(app);
1134
+ agent = await authAsUser(app, "admin");
1135
+
1136
+ const res = await agent
1137
+ .patch(`/food/${apple._id}/tags/healthy`)
1138
+ .send({tags: "unhealthy"})
1139
+ .expect(403);
1140
+ expect(res.body.title).toBe("Update not allowed");
1141
+ });
1142
+
1143
+ it("array operation preUpdate error for array DELETE is handled", async () => {
1144
+ app.use(
1145
+ "/food",
1146
+ modelRouter(FoodModel, {
1147
+ allowAnonymous: true,
1148
+ permissions: {
1149
+ create: [Permissions.IsAdmin],
1150
+ delete: [Permissions.IsAdmin],
1151
+ list: [Permissions.IsAdmin],
1152
+ read: [Permissions.IsAdmin],
1153
+ update: [Permissions.IsAdmin],
1154
+ },
1155
+ preUpdate: () => {
1156
+ throw new Error("preUpdate error during delete");
1157
+ },
1158
+ })
1159
+ );
1160
+ server = supertest(app);
1161
+ agent = await authAsUser(app, "admin");
1162
+
1163
+ const res = await agent.delete(`/food/${apple._id}/tags/healthy`).expect(400);
1164
+ expect(res.body.title).toContain("preUpdate hook error");
1165
+ });
1166
+
1167
+ it("array operation postUpdate error is handled", async () => {
1168
+ app.use(
1169
+ "/food",
1170
+ modelRouter(FoodModel, {
1171
+ allowAnonymous: true,
1172
+ permissions: {
1173
+ create: [Permissions.IsAdmin],
1174
+ delete: [Permissions.IsAdmin],
1175
+ list: [Permissions.IsAdmin],
1176
+ read: [Permissions.IsAdmin],
1177
+ update: [Permissions.IsAdmin],
1178
+ },
1179
+ postUpdate: () => {
1180
+ throw new Error("postUpdate array failed");
1181
+ },
1182
+ })
1183
+ );
1184
+ server = supertest(app);
1185
+ agent = await authAsUser(app, "admin");
1186
+
1187
+ const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(400);
1188
+ expect(res.body.title).toContain("PATCH Post Update error");
1189
+ });
1190
+
1191
+ it("array operation denied without update permission", async () => {
1192
+ app.use(
1193
+ "/food",
1194
+ modelRouter(FoodModel, {
1195
+ allowAnonymous: true,
1196
+ permissions: {
1197
+ create: [Permissions.IsAdmin],
1198
+ delete: [Permissions.IsAdmin],
1199
+ list: [Permissions.IsAny],
1200
+ read: [Permissions.IsAny],
1201
+ update: [Permissions.IsAdmin],
1202
+ },
1203
+ })
1204
+ );
1205
+ server = supertest(app);
1206
+ agent = await authAsUser(app, "notAdmin");
1207
+
1208
+ const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(405);
1209
+ expect(res.body.title).toContain("Access to PATCH");
1210
+ });
1211
+
1212
+ it("array operation on non-existent document returns 404", async () => {
1213
+ app.use(
1214
+ "/food",
1215
+ modelRouter(FoodModel, {
1216
+ allowAnonymous: true,
1217
+ permissions: {
1218
+ create: [Permissions.IsAdmin],
1219
+ delete: [Permissions.IsAdmin],
1220
+ list: [Permissions.IsAdmin],
1221
+ read: [Permissions.IsAdmin],
1222
+ update: [Permissions.IsAdmin],
1223
+ },
1224
+ })
1225
+ );
1226
+ server = supertest(app);
1227
+ agent = await authAsUser(app, "admin");
1228
+
1229
+ const fakeId = "000000000000000000000000";
1230
+ const res = await agent.post(`/food/${fakeId}/tags`).send({tags: "organic"}).expect(404);
1231
+ expect(res.body.title).toContain("Could not find document to PATCH");
1232
+ });
1233
+
1234
+ it("array operation denied when user cannot update specific doc", async () => {
1235
+ // Create food owned by admin, then try to update as notAdmin
1236
+ app.use(
1237
+ "/food",
1238
+ modelRouter(FoodModel, {
1239
+ allowAnonymous: true,
1240
+ permissions: {
1241
+ create: [Permissions.IsAuthenticated],
1242
+ delete: [Permissions.IsAuthenticated],
1243
+ list: [Permissions.IsAuthenticated],
1244
+ read: [Permissions.IsAuthenticated],
1245
+ update: [Permissions.IsOwner],
1246
+ },
1247
+ })
1248
+ );
1249
+ server = supertest(app);
1250
+ // Login as notAdmin and try to update admin's food (apple)
1251
+ agent = await authAsUser(app, "notAdmin");
1252
+
1253
+ const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(403);
1254
+ expect(res.body.title).toContain("Patch not allowed");
1255
+ });
1256
+
1257
+ it("array operation transform error is handled", async () => {
1258
+ app.use(
1259
+ "/food",
1260
+ modelRouter(FoodModel, {
1261
+ allowAnonymous: true,
1262
+ permissions: {
1263
+ create: [Permissions.IsAdmin],
1264
+ delete: [Permissions.IsAdmin],
1265
+ list: [Permissions.IsAdmin],
1266
+ read: [Permissions.IsAdmin],
1267
+ update: [Permissions.IsAdmin],
1268
+ },
1269
+ transformer: AdminOwnerTransformer({
1270
+ adminWriteFields: ["name"],
1271
+ }),
1272
+ })
1273
+ );
1274
+ server = supertest(app);
1275
+ agent = await authAsUser(app, "admin");
1276
+
1277
+ // Try to update tags field, which is not in the allowed write fields
1278
+ const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(403);
1279
+ expect(res.body.title).toContain("cannot write fields");
1280
+ });
1281
+ });
1282
+
1283
+ describe("transformer errors", () => {
1284
+ let admin: any;
1285
+ let spinach: Food;
1286
+ let agent: TestAgent;
1287
+
1288
+ beforeEach(async () => {
1289
+ [admin] = await setupDb();
1290
+
1291
+ spinach = await FoodModel.create({
1292
+ calories: 1,
1293
+ created: new Date("2021-12-03T00:00:20.000Z"),
1294
+ hidden: false,
1295
+ name: "Spinach",
1296
+ ownerId: admin._id,
1297
+ source: {
1298
+ name: "Brand",
1299
+ },
1300
+ });
1301
+
1302
+ app = getBaseServer();
1303
+ setupAuth(app, UserModel as any);
1304
+ addAuthRoutes(app, UserModel as any);
1305
+ });
1306
+
1307
+ it("transform error in create is handled", async () => {
1308
+ app.use(
1309
+ "/food",
1310
+ modelRouter(FoodModel, {
1311
+ allowAnonymous: true,
1312
+ permissions: {
1313
+ create: [Permissions.IsAny],
1314
+ delete: [Permissions.IsAny],
1315
+ list: [Permissions.IsAny],
1316
+ read: [Permissions.IsAny],
1317
+ update: [Permissions.IsAny],
1318
+ },
1319
+ transformer: AdminOwnerTransformer({
1320
+ // Only allow 'name' to be written, so 'calories' will throw
1321
+ anonWriteFields: ["name"],
1322
+ }),
1323
+ })
1324
+ );
1325
+ server = supertest(app);
1326
+
1327
+ const res = await server.post("/food").send({calories: 15, name: "Broccoli"}).expect(400);
1328
+ expect(res.body.title).toContain("cannot write fields");
1329
+ });
1330
+
1331
+ it("transform error in patch is handled", async () => {
1332
+ app.use(
1333
+ "/food",
1334
+ modelRouter(FoodModel, {
1335
+ allowAnonymous: true,
1336
+ permissions: {
1337
+ create: [Permissions.IsAny],
1338
+ delete: [Permissions.IsAny],
1339
+ list: [Permissions.IsAny],
1340
+ read: [Permissions.IsAny],
1341
+ update: [Permissions.IsAny],
1342
+ },
1343
+ transformer: AdminOwnerTransformer({
1344
+ // Only allow 'name' to be written, so 'calories' will throw
1345
+ anonWriteFields: ["name"],
1346
+ }),
1347
+ })
1348
+ );
1349
+ server = supertest(app);
1350
+
1351
+ const res = await server.patch(`/food/${spinach._id}`).send({calories: 100}).expect(403);
1352
+ expect(res.body.title).toContain("cannot write fields");
1353
+ });
1354
+
1355
+ it("model.create validation error is handled", async () => {
1356
+ // Use a model that has required fields
1357
+ const {RequiredModel} = await import("./tests");
1358
+
1359
+ app.use(
1360
+ "/required",
1361
+ modelRouter(RequiredModel, {
1362
+ allowAnonymous: true,
1363
+ permissions: {
1364
+ create: [Permissions.IsAny],
1365
+ delete: [Permissions.IsAny],
1366
+ list: [Permissions.IsAny],
1367
+ read: [Permissions.IsAny],
1368
+ update: [Permissions.IsAny],
1369
+ },
1370
+ })
1371
+ );
1372
+ server = supertest(app);
1373
+
1374
+ // Send without required 'name' field
1375
+ const res = await server.post("/required").send({about: "test"}).expect(400);
1376
+ expect(res.body.title).toContain("Required");
1377
+ });
1378
+
1379
+ it("preDelete hook throwing APIError is re-thrown", async () => {
1380
+ app.use(
1381
+ "/food",
1382
+ modelRouter(FoodModel, {
1383
+ allowAnonymous: true,
1384
+ permissions: {
1385
+ create: [Permissions.IsAny],
1386
+ delete: [Permissions.IsAny],
1387
+ list: [Permissions.IsAny],
1388
+ read: [Permissions.IsAny],
1389
+ update: [Permissions.IsAny],
1390
+ },
1391
+ preDelete: () => {
1392
+ throw new APIError({
1393
+ disableExternalErrorTracking: true,
1394
+ status: 400,
1395
+ title: "Custom preDelete APIError",
1396
+ });
1397
+ },
1398
+ })
1399
+ );
1400
+ server = supertest(app);
1401
+ agent = await authAsUser(app, "notAdmin");
1402
+
1403
+ const res = await agent.delete(`/food/${spinach._id}`).expect(400);
1404
+ expect(res.body.title).toBe("Custom preDelete APIError");
1405
+ expect(res.body.disableExternalErrorTracking).toBe(true);
1406
+ });
1407
+ });
1408
+
1409
+ describe("special query params", () => {
1410
+ let admin: any;
1411
+
1412
+ beforeEach(async () => {
1413
+ [admin] = await setupDb();
1414
+
1415
+ await FoodModel.create({
1416
+ calories: 1,
1417
+ created: new Date("2021-12-03T00:00:20.000Z"),
1418
+ hidden: false,
1419
+ name: "Spinach",
1420
+ ownerId: admin._id,
1421
+ });
1422
+
1423
+ app = getBaseServer();
1424
+ setupAuth(app, UserModel as any);
1425
+ addAuthRoutes(app, UserModel as any);
1426
+ });
1427
+
1428
+ it("period query param is stripped from query", async () => {
1429
+ app.use(
1430
+ "/food",
1431
+ modelRouter(FoodModel, {
1432
+ allowAnonymous: true,
1433
+ permissions: {
1434
+ create: [Permissions.IsAny],
1435
+ delete: [Permissions.IsAny],
1436
+ list: [Permissions.IsAny],
1437
+ read: [Permissions.IsAny],
1438
+ update: [Permissions.IsAny],
1439
+ },
1440
+ queryFields: ["name", "period"],
1441
+ queryFilter: (_user, query) => {
1442
+ // Simulate a queryFilter that accepts and processes period
1443
+ if (query?.period) {
1444
+ // Period is processed but shouldn't be passed to mongo
1445
+ return query;
1446
+ }
1447
+ return query ?? {};
1448
+ },
1449
+ })
1450
+ );
1451
+ server = supertest(app);
1452
+
1453
+ // period should be accepted and processed without error
1454
+ const res = await server.get("/food?period=weekly").expect(200);
1455
+ expect(res.body.data).toBeDefined();
1456
+ });
1457
+
1458
+ it("query with false value", async () => {
1459
+ // Create a food that is hidden
1460
+ await FoodModel.create({
1461
+ calories: 50,
1462
+ created: new Date("2021-12-04T00:00:20.000Z"),
1463
+ hidden: true,
1464
+ name: "HiddenFood",
1465
+ ownerId: admin._id,
1466
+ });
1467
+
1468
+ app.use(
1469
+ "/food",
1470
+ modelRouter(FoodModel, {
1471
+ allowAnonymous: true,
1472
+ permissions: {
1473
+ create: [Permissions.IsAny],
1474
+ delete: [Permissions.IsAny],
1475
+ list: [Permissions.IsAny],
1476
+ read: [Permissions.IsAny],
1477
+ update: [Permissions.IsAny],
1478
+ },
1479
+ queryFields: ["name", "hidden"],
1480
+ })
1481
+ );
1482
+ server = supertest(app);
1483
+
1484
+ // Query for non-hidden foods using ?hidden=false
1485
+ const res = await server.get("/food?hidden=false").expect(200);
1486
+ expect(res.body.data.every((f: any) => f.hidden === false)).toBe(true);
1487
+ });
1488
+
1489
+ it("$search query triggers special handling code path", async () => {
1490
+ // The $search code path just accesses the collection but doesn't do anything with it
1491
+ // This test verifies the code path is exercised
1492
+ app.use(
1493
+ "/food",
1494
+ modelRouter(FoodModel, {
1495
+ allowAnonymous: true,
1496
+ permissions: {
1497
+ create: [Permissions.IsAny],
1498
+ delete: [Permissions.IsAny],
1499
+ list: [Permissions.IsAny],
1500
+ read: [Permissions.IsAny],
1501
+ update: [Permissions.IsAny],
1502
+ },
1503
+ // Need to include $search in queryFields for it to pass validation
1504
+ queryFields: ["name", "$search"],
1505
+ })
1506
+ );
1507
+ server = supertest(app);
1508
+
1509
+ // The $search will be added to the query params, triggering the special handling
1510
+ // Even though the code doesn't actually do anything useful with it (stub for Atlas)
1511
+ const res = await server.get("/food?$search=test");
1512
+ // May return 500 because $search is passed to Mongo which doesn't support it without Atlas
1513
+ // The important thing is we've exercised the code path
1514
+ expect(res.status === 200 || res.status === 500).toBe(true);
1515
+ });
1516
+
1517
+ it("$autocomplete query triggers special handling code path", async () => {
1518
+ app.use(
1519
+ "/food",
1520
+ modelRouter(FoodModel, {
1521
+ allowAnonymous: true,
1522
+ permissions: {
1523
+ create: [Permissions.IsAny],
1524
+ delete: [Permissions.IsAny],
1525
+ list: [Permissions.IsAny],
1526
+ read: [Permissions.IsAny],
1527
+ update: [Permissions.IsAny],
1528
+ },
1529
+ queryFields: ["name", "$autocomplete"],
1530
+ })
1531
+ );
1532
+ server = supertest(app);
1533
+
1534
+ const res = await server.get("/food?$autocomplete=test");
1535
+ expect(res.status === 200 || res.status === 500).toBe(true);
1536
+ });
1537
+ });
1538
+
1539
+ describe("addPopulateToQuery", () => {
1540
+ it("returns query unchanged with no populate paths", async () => {
1541
+ await setupDb();
1542
+ const query = FoodModel.find({});
1543
+ const result = addPopulateToQuery(query, undefined);
1544
+ expect(result).toBe(query);
1545
+ });
1546
+
1547
+ it("returns query unchanged with empty populate paths", async () => {
1548
+ await setupDb();
1549
+ const query = FoodModel.find({});
1550
+ const result = addPopulateToQuery(query, []);
1551
+ expect(result).toBe(query);
1552
+ });
1553
+
1554
+ it("applies multiple populate paths", async () => {
1555
+ await setupDb();
1556
+ const query = FoodModel.find({});
1557
+ const result = addPopulateToQuery(query, [
1558
+ {fields: ["email"], path: "ownerId"},
1559
+ {fields: ["name"], path: "eatenBy"},
1560
+ ]);
1561
+ // The result should be a query with populate applied
1562
+ expect(result).toBeDefined();
1563
+ });
1564
+ });
1565
+
1566
+ describe("soft delete with isDeleted plugin", () => {
1567
+ let admin: any;
1568
+ let agent: TestAgent;
1569
+
1570
+ beforeEach(async () => {
1571
+ [admin] = await setupDb();
1572
+
1573
+ app = getBaseServer();
1574
+ setupAuth(app, UserModel as any);
1575
+ addAuthRoutes(app, UserModel as any);
1576
+ });
1577
+
1578
+ it("soft deletes user with deleted field", async () => {
1579
+ // UserModel has the isDisabledPlugin which adds a 'disabled' field,
1580
+ // but we need to test the 'deleted' field check.
1581
+ // Let's use a model that has the deleted field.
1582
+ app.use(
1583
+ "/users",
1584
+ modelRouter(UserModel, {
1585
+ allowAnonymous: true,
1586
+ permissions: {
1587
+ create: [Permissions.IsAny],
1588
+ delete: [Permissions.IsAny],
1589
+ list: [Permissions.IsAny],
1590
+ read: [Permissions.IsAny],
1591
+ update: [Permissions.IsAny],
1592
+ },
1593
+ })
1594
+ );
1595
+ server = supertest(app);
1596
+ agent = await authAsUser(app, "notAdmin");
1597
+
1598
+ // Delete a user - this should use deleteOne since User doesn't have deleted field
1599
+ const res = await agent.delete(`/users/${admin._id}`).expect(204);
1600
+ expect(res.body).toEqual({});
1601
+
1602
+ // Verify user was deleted
1603
+ const deletedUser = await UserModel.findById(admin._id);
1604
+ expect(deletedUser).toBeNull();
1605
+ });
1606
+ });
1607
+
1608
+ describe("populate in create", () => {
1609
+ let admin: any;
1610
+
1611
+ beforeEach(async () => {
1612
+ [admin] = await setupDb();
1613
+
1614
+ await FoodModel.create({
1615
+ calories: 1,
1616
+ created: new Date("2021-12-03T00:00:20.000Z"),
1617
+ hidden: false,
1618
+ name: "Spinach",
1619
+ ownerId: admin._id,
1620
+ });
1621
+
1622
+ app = getBaseServer();
1623
+ setupAuth(app, UserModel as any);
1624
+ addAuthRoutes(app, UserModel as any);
1625
+ });
1626
+
1627
+ it("handles populate with valid path in create", async () => {
1628
+ // Test that valid populate works in create flow
1629
+ app.use(
1630
+ "/food",
1631
+ modelRouter(FoodModel, {
1632
+ allowAnonymous: true,
1633
+ permissions: {
1634
+ create: [Permissions.IsAny],
1635
+ delete: [Permissions.IsAny],
1636
+ list: [Permissions.IsAny],
1637
+ read: [Permissions.IsAny],
1638
+ update: [Permissions.IsAny],
1639
+ },
1640
+ populatePaths: [{fields: ["email"], path: "ownerId"}],
1641
+ })
1642
+ );
1643
+ server = supertest(app);
1644
+
1645
+ const res = await server
1646
+ .post("/food")
1647
+ .send({calories: 15, name: "Broccoli", ownerId: admin._id})
1648
+ .expect(201);
1649
+ expect(res.body.data.name).toBe("Broccoli");
1650
+ // Verify populate worked - ownerId should be an object with email
1651
+ expect(res.body.data.ownerId.email).toBe(admin.email);
1652
+ });
1653
+ });
1654
+
1655
+ describe("save error handling", () => {
1656
+ let admin: any;
1657
+ let spinach: Food;
1658
+
1659
+ beforeEach(async () => {
1660
+ [admin] = await setupDb();
1661
+
1662
+ spinach = await FoodModel.create({
1663
+ calories: 1,
1664
+ created: new Date("2021-12-03T00:00:20.000Z"),
1665
+ hidden: false,
1666
+ name: "Spinach",
1667
+ ownerId: admin._id,
1668
+ source: {
1669
+ name: "Brand",
1670
+ },
1671
+ });
1672
+
1673
+ app = getBaseServer();
1674
+ setupAuth(app, UserModel as any);
1675
+ addAuthRoutes(app, UserModel as any);
1676
+ });
1677
+
1678
+ it("handles patch save error with validation failure", async () => {
1679
+ // The FoodModel has strict: "throw" which will cause validation errors for unknown fields
1680
+ app.use(
1681
+ "/food",
1682
+ modelRouter(FoodModel, {
1683
+ allowAnonymous: true,
1684
+ permissions: {
1685
+ create: [Permissions.IsAny],
1686
+ delete: [Permissions.IsAny],
1687
+ list: [Permissions.IsAny],
1688
+ read: [Permissions.IsAny],
1689
+ update: [Permissions.IsAny],
1690
+ },
1691
+ })
1692
+ );
1693
+ server = supertest(app);
1694
+
1695
+ // Try to patch with an invalid field (will be caught by strict: "throw")
1696
+ const res = await server
1697
+ .patch(`/food/${spinach._id}`)
1698
+ .send({invalidField: "value"})
1699
+ .expect(400);
1700
+ expect(res.body.title).toContain("preUpdate hook save error");
1701
+ });
1702
+ });
1703
+
1704
+ describe("body undefined after transform without preCreate", () => {
1705
+ beforeEach(async () => {
1706
+ await setupDb();
1707
+
1708
+ app = getBaseServer();
1709
+ setupAuth(app, UserModel as any);
1710
+ addAuthRoutes(app, UserModel as any);
1711
+ });
1712
+
1713
+ it("handles undefined body after transform when no preCreate", async () => {
1714
+ // Create a transformer that returns undefined
1715
+ app.use(
1716
+ "/food",
1717
+ modelRouter(FoodModel, {
1718
+ allowAnonymous: true,
1719
+ permissions: {
1720
+ create: [Permissions.IsAny],
1721
+ delete: [Permissions.IsAny],
1722
+ list: [Permissions.IsAny],
1723
+ read: [Permissions.IsAny],
1724
+ update: [Permissions.IsAny],
1725
+ },
1726
+ transformer: {
1727
+ transform: () => undefined,
1728
+ },
1729
+ })
1730
+ );
1731
+ server = supertest(app);
1732
+
1733
+ const res = await server.post("/food").send({calories: 15, name: "Broccoli"}).expect(400);
1734
+ expect(res.body.title).toBe("Invalid request body");
1735
+ expect(res.body.detail).toBe("Body is undefined");
1736
+ });
1737
+ });
1738
+
1739
+ describe("soft delete with deleted field", () => {
1740
+ let _admin: any;
1741
+ let agent: TestAgent;
1742
+
1743
+ beforeEach(async () => {
1744
+ [_admin] = await setupDb();
1745
+
1746
+ app = getBaseServer();
1747
+ setupAuth(app, UserModel as any);
1748
+ addAuthRoutes(app, UserModel as any);
1749
+ });
1750
+
1751
+ it("soft deletes document with deleted field using isDeletedPlugin", async () => {
1752
+ // Create a test schema with the isDeletedPlugin
1753
+ const mongoose = await import("mongoose");
1754
+
1755
+ // Create a temporary model with the deleted field
1756
+ const softDeleteSchema = new mongoose.Schema({
1757
+ deleted: {default: false, type: Boolean},
1758
+ name: String,
1759
+ });
1760
+ // Manually add the deleted field (simulating what isDeletedPlugin does)
1761
+ // The schema already has the deleted field, so it should use soft delete
1762
+
1763
+ // Check if the model already exists to avoid OverwriteModelError
1764
+ let SoftDeleteModel;
1765
+ try {
1766
+ SoftDeleteModel = mongoose.model("SoftDeleteTest");
1767
+ } catch {
1768
+ SoftDeleteModel = mongoose.model("SoftDeleteTest", softDeleteSchema);
1769
+ }
1770
+
1771
+ // Clean up any existing documents
1772
+ await SoftDeleteModel.deleteMany({});
1773
+
1774
+ // Create a test document
1775
+ const testDoc = await SoftDeleteModel.create({name: "TestItem"});
1776
+
1777
+ app.use(
1778
+ "/softdelete",
1779
+ modelRouter(SoftDeleteModel, {
1780
+ allowAnonymous: true,
1781
+ permissions: {
1782
+ create: [Permissions.IsAny],
1783
+ delete: [Permissions.IsAny],
1784
+ list: [Permissions.IsAny],
1785
+ read: [Permissions.IsAny],
1786
+ update: [Permissions.IsAny],
1787
+ },
1788
+ })
1789
+ );
1790
+ server = supertest(app);
1791
+ agent = await authAsUser(app, "notAdmin");
1792
+
1793
+ // Delete should soft delete (set deleted: true) instead of hard delete
1794
+ await agent.delete(`/softdelete/${testDoc._id}`).expect(204);
1795
+
1796
+ // Verify document was soft deleted (not hard deleted)
1797
+ const softDeleted = await SoftDeleteModel.findById(testDoc._id);
1798
+ expect(softDeleted).not.toBeNull();
1799
+ expect(softDeleted?.deleted).toBe(true);
1800
+
1801
+ // Clean up
1802
+ await SoftDeleteModel.deleteMany({});
1803
+ });
1804
+ });
1805
+
1065
1806
  describe("array operation with undefined preUpdate return", () => {
1066
1807
  let admin: any;
1067
1808
  let apple: Food;