@jskit-ai/users-core 0.2.15 → 0.2.17
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/CHANGELOG.md +26 -0
- package/package.json +24 -17
- package/patterns/user-administration-server/PATTERN.md +63 -10
- package/patterns/user-administration-server/example/packages/users/package.json +5 -4
- package/patterns/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
- package/patterns/user-administration-server/example/packages/users/src/shared/index.js +1 -1
- package/patterns/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
- package/patterns/user-administration-server/example/packages/users-workspace/package.json +11 -5
- package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
- package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
- package/src/server/UsersFeature.js +10 -6
- package/src/server/UsersIdentityProvider.js +13 -29
- package/src/server/accountNotifications/accountNotificationsActions.js +3 -3
- package/src/server/accountNotifications/accountNotificationsRoutes.js +3 -3
- package/src/server/accountPreferences/accountPreferencesActions.js +3 -3
- package/src/server/accountPreferences/accountPreferencesRoutes.js +3 -3
- package/src/server/accountProfile/accountProfileActions.js +9 -9
- package/src/server/accountProfile/accountProfileRoutes.js +5 -5
- package/src/server/accountSecurity/accountSecurityActions.js +10 -10
- package/src/server/accountSecurity/accountSecurityRoutes.js +9 -9
- package/src/server/common/repositories/recordsByIds.js +38 -0
- package/src/server/common/repositories/userProfilesRepository.js +261 -146
- package/src/server/common/repositories/userSettingsRepository.js +37 -49
- package/src/server/common/services/authProfileSyncService.js +3 -5
- package/src/server/types.js +9 -1
- package/src/server/usersIdentity.js +11 -11
- package/src/server/usersRuntime.js +13 -11
- package/src/shared/resources/userProfileResource.js +43 -13
- package/src/shared/resources/userSettingsResource.js +35 -29
- package/test/accountSecurityService.test.js +2 -2
- package/test/authProfileSyncService.test.js +13 -9
- package/test/exportsContract.test.js +2 -0
- package/test/featureRuntime.test.js +63 -20
- package/test/i18nCodes.test.js +6 -10
- package/test/listByIds.mysql.test.js +5 -0
- package/test/listByIds.postgres.test.js +6 -0
- package/test/repositories.mysql.test.js +384 -0
- package/test/resourcesCanonical.test.js +58 -22
- package/test/support/listByIdsCases.js +115 -0
- package/test/support/usersDatabases.js +135 -0
- package/test/userSettingsInternalResource.test.js +3 -3
- package/test/userSettingsResource.test.js +3 -3
- package/test/usersPackageScaffoldContract.test.js +70 -12
- package/test/usersRouteRequestInputValidator.test.js +2 -2
- package/test/usersRouteResources.test.js +73 -29
- package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
- package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
- package/test/repositoryContracts.test.js +0 -596
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import knexLib from "knex";
|
|
2
|
+
import { after } from "node:test";
|
|
3
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
+
import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
|
|
5
|
+
import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
|
|
6
|
+
import usersInitial from "../../migrations/users_core_generic_initial.cjs";
|
|
7
|
+
import usersUsername from "../../migrations/users_core_profile_username.cjs";
|
|
8
|
+
import usersUpdatedAt from "../../migrations/users_core_profile_updated_at.cjs";
|
|
9
|
+
import { createUsersExtensions } from "../../src/server/usersExtensions.js";
|
|
10
|
+
import { createUsersIdentity } from "../../src/server/usersIdentity.js";
|
|
11
|
+
import { userProfileTableResource } from "../../src/shared/resources/userProfileResource.js";
|
|
12
|
+
import { userSettingsTableResource } from "../../src/shared/resources/userSettingsResource.js";
|
|
13
|
+
|
|
14
|
+
// The migrated users tables in a database of the test file's own, made on first use and dropped when the file ends:
|
|
15
|
+
// on MariaDB/MySQL a database named after TEST_DB_NAME with the file's suffix, on PostgreSQL a schema of that name in
|
|
16
|
+
// TEST_DB_NAME. Each test keeps to its own users.
|
|
17
|
+
const MIGRATIONS = [usersInitial, usersUsername, usersUpdatedAt];
|
|
18
|
+
|
|
19
|
+
// A PostgreSQL test on a run for another database, such as CI's MariaDB run, is left to the PostgreSQL run.
|
|
20
|
+
const POSTGRES_ELSEWHERE = process.env.DB_CLIENT && process.env.DB_CLIENT !== "pg"
|
|
21
|
+
? `a PostgreSQL test, on a ${process.env.DB_CLIENT} run`
|
|
22
|
+
: false;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* users.profiles, users.settings and the projector on `knex`'s users tables, owned as UsersIdentityProvider owns
|
|
26
|
+
* them; `rowPolicy` narrows the users table as an owner's row policy would.
|
|
27
|
+
* @param {import("knex").Knex} knex
|
|
28
|
+
* @param {{ rowPolicy?: Function }} [options]
|
|
29
|
+
*/
|
|
30
|
+
async function ownUsers(knex, { rowPolicy } = {}) {
|
|
31
|
+
const runtime = await createTestResourceRuntime({ knex, logger: silentLogger });
|
|
32
|
+
const profilesEntry = rowPolicy ? { resource: userProfileTableResource, rowPolicy } : userProfileTableResource;
|
|
33
|
+
const resources = await runtime.own("users.identity", [profilesEntry, userSettingsTableResource]);
|
|
34
|
+
const identity = createUsersIdentity({ resources, extensions: createUsersExtensions() });
|
|
35
|
+
// Background work's context, as a feature declaring a systemScope receives it.
|
|
36
|
+
const systemContext = runtime.declareSystemScope("users.identity", "import users")("users test import");
|
|
37
|
+
return Object.freeze({ knex, resources, systemContext, ...identity });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function migratedUsers(knex) {
|
|
41
|
+
for (const migration of MIGRATIONS) await migration.up(knex);
|
|
42
|
+
const owned = await ownUsers(knex);
|
|
43
|
+
return Object.freeze({ ...owned, ownedWith: (options) => ownUsers(knex, options) });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function openMysqlDatabase(suffix, cleanups) {
|
|
47
|
+
const name = `${requireTestDatabase(process.env)}_${suffix}`;
|
|
48
|
+
if (name.length > 64) throw new Error(`Test database name ${name} is longer than MySQL's 64 characters.`);
|
|
49
|
+
const server = {
|
|
50
|
+
host: process.env.DB_HOST,
|
|
51
|
+
port: Number(process.env.DB_PORT) || 3306,
|
|
52
|
+
user: process.env.DB_USER,
|
|
53
|
+
password: process.env.DB_PASSWORD,
|
|
54
|
+
// The mysql2 options database-runtime's connection gives an application, so records read as apps see them.
|
|
55
|
+
supportBigNumbers: true,
|
|
56
|
+
bigNumberStrings: true,
|
|
57
|
+
dateStrings: ["DATE"],
|
|
58
|
+
timezone: "Z"
|
|
59
|
+
};
|
|
60
|
+
const admin = knexLib({ client: "mysql2", connection: server, pool: { min: 0, max: 1 } });
|
|
61
|
+
const knex = knexLib({ client: "mysql2", connection: { ...server, database: name }, pool: { min: 0, max: 6 } });
|
|
62
|
+
cleanups.push(async () => {
|
|
63
|
+
try {
|
|
64
|
+
await knex.destroy();
|
|
65
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
66
|
+
} finally {
|
|
67
|
+
await admin.destroy();
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
await admin.raw("DROP DATABASE IF EXISTS ??", [name]);
|
|
71
|
+
await admin.raw("CREATE DATABASE ??", [name]);
|
|
72
|
+
return migratedUsers(knex);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function openPostgresSchema(suffix, cleanups) {
|
|
76
|
+
const database = requireTestDatabase(process.env);
|
|
77
|
+
const schema = `${database}_${suffix}_${process.pid}`;
|
|
78
|
+
if (schema.length > 63) throw new Error(`Test schema name ${schema} is longer than PostgreSQL's 63 characters.`);
|
|
79
|
+
const connection = {
|
|
80
|
+
host: process.env.DB_HOST,
|
|
81
|
+
port: Number(process.env.DB_PORT) || 5432,
|
|
82
|
+
user: process.env.DB_USER,
|
|
83
|
+
password: process.env.DB_PASSWORD,
|
|
84
|
+
database
|
|
85
|
+
};
|
|
86
|
+
const admin = knexLib({ client: "pg", connection, pool: { min: 0, max: 1 } });
|
|
87
|
+
const knex = knexLib({ client: "pg", connection, searchPath: [schema], pool: { min: 0, max: 6 } });
|
|
88
|
+
cleanups.push(async () => {
|
|
89
|
+
try {
|
|
90
|
+
await knex.destroy();
|
|
91
|
+
await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
|
|
92
|
+
} finally {
|
|
93
|
+
await admin.destroy();
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
await admin.raw("DROP SCHEMA IF EXISTS ?? CASCADE", [schema]);
|
|
97
|
+
await admin.raw("CREATE SCHEMA ??", [schema]);
|
|
98
|
+
return migratedUsers(knex);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function fileDatabase(openDatabase, suffix) {
|
|
102
|
+
const cleanups = [];
|
|
103
|
+
let opening = null;
|
|
104
|
+
after(async () => {
|
|
105
|
+
if (opening) await opening.catch(() => {});
|
|
106
|
+
for (const cleanup of cleanups) await cleanup();
|
|
107
|
+
});
|
|
108
|
+
return Object.freeze({
|
|
109
|
+
open() {
|
|
110
|
+
opening ??= openDatabase(suffix, cleanups);
|
|
111
|
+
return opening;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The file's MariaDB/MySQL database: call it at the file's top level, then `await open()` in each test after
|
|
118
|
+
* requireTestDatabase(). The database is made by the first test that opens it and dropped after the file's tests.
|
|
119
|
+
* Its `ownedWith({ rowPolicy })` owns the same tables again, narrowed.
|
|
120
|
+
* @param {string} suffix A short name unique to the test file, such as "users_repos".
|
|
121
|
+
*/
|
|
122
|
+
function usersDatabase(suffix) {
|
|
123
|
+
return fileDatabase(openMysqlDatabase, suffix);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The file's PostgreSQL schema in TEST_DB_NAME, used as usersDatabase() is. Its tests skip with
|
|
128
|
+
* POSTGRES_ELSEWHERE on a run for another database.
|
|
129
|
+
* @param {string} suffix A short name unique to the test file.
|
|
130
|
+
*/
|
|
131
|
+
function postgresUsersDatabase(suffix) {
|
|
132
|
+
return fileDatabase(openPostgresSchema, suffix);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export { POSTGRES_ELSEWHERE, postgresUsersDatabase, usersDatabase };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import test from "node:test";
|
|
3
|
-
import {
|
|
3
|
+
import { userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
|
|
4
4
|
|
|
5
5
|
test("shared user settings resource declares user_id as the resource id column", () => {
|
|
6
|
-
assert.equal(
|
|
7
|
-
assert.equal(
|
|
6
|
+
assert.equal(userSettingsTableResource.idProperty, "user_id");
|
|
7
|
+
assert.equal(userSettingsTableResource.schema.id?.storage?.column, "user_id");
|
|
8
8
|
});
|
|
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
|
|
|
3
3
|
import { validateOperationSection } from "@jskit-ai/http-runtime/shared/validators/operationValidation";
|
|
4
4
|
import {
|
|
5
5
|
USER_SETTINGS_ALL_KEYS,
|
|
6
|
-
|
|
6
|
+
userSettingsContract
|
|
7
7
|
} from "../src/shared/resources/userSettingsResource.js";
|
|
8
8
|
|
|
9
9
|
function parseBody(operation, payload = {}) {
|
|
@@ -15,7 +15,7 @@ function parseBody(operation, payload = {}) {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
test("user settings preferences update keeps required string validation", async () => {
|
|
18
|
-
const parsed = await parseBody(
|
|
18
|
+
const parsed = await parseBody(userSettingsContract.operations.preferencesUpdate, {
|
|
19
19
|
theme: " "
|
|
20
20
|
});
|
|
21
21
|
|
|
@@ -24,7 +24,7 @@ test("user settings preferences update keeps required string validation", async
|
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
test("user settings notifications update rejects non-boolean values", async () => {
|
|
27
|
-
const parsed = await parseBody(
|
|
27
|
+
const parsed = await parseBody(userSettingsContract.operations.notificationsUpdate, {
|
|
28
28
|
productUpdates: "yes"
|
|
29
29
|
});
|
|
30
30
|
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import test from "node:test";
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
6
|
import packageJson from "../package.json" with { type: "json" };
|
|
7
|
+
import { userProfileTableResource } from "../src/shared/resources/userProfileResource.js";
|
|
7
8
|
|
|
8
9
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
9
10
|
const patternRoot = path.join(packageRoot, "patterns", "user-administration-server");
|
|
@@ -13,9 +14,11 @@ test("users-core publishes agent-readable administration patterns and package-ow
|
|
|
13
14
|
assert.deepEqual(packageJson.jskit?.migrations, { directories: ["migrations"] });
|
|
14
15
|
|
|
15
16
|
const pattern = await readFile(path.join(patternRoot, "PATTERN.md"), "utf8");
|
|
16
|
-
assert.match(pattern, /
|
|
17
|
+
assert.match(pattern, /defineCrudFeature\(\)/);
|
|
18
|
+
assert.match(pattern, /ownerRepository: "users\.profiles"/);
|
|
17
19
|
assert.match(pattern, /Workspace operations are scoped before repository access/);
|
|
18
20
|
assert.match(pattern, /null\/cleared fields/);
|
|
21
|
+
assert.match(pattern, /defineCrudContract\(userProfileTableResource,/);
|
|
19
22
|
assert.doesNotMatch(pattern, /createCrudJsonApiModule/);
|
|
20
23
|
});
|
|
21
24
|
|
|
@@ -32,9 +35,9 @@ test("global user administration example is one declarative CRUD feature", async
|
|
|
32
35
|
assert.equal(packageManifest.name, "@app/users");
|
|
33
36
|
assert.equal(packageManifest.jskit?.mutations, undefined);
|
|
34
37
|
assert.deepEqual(packageManifest.jskit?.capabilities?.provides, ["app.users"]);
|
|
35
|
-
assert.match(feature, /
|
|
38
|
+
assert.match(feature, /defineCrudFeature/);
|
|
36
39
|
assert.match(feature, /surface: "home"/);
|
|
37
|
-
assert.match(feature, /
|
|
40
|
+
assert.match(feature, /ownerRepository: "users\.profiles"/);
|
|
38
41
|
assert.doesNotMatch(feature, /\.make\(|\.singleton\(|containerToken|repositoryToken|serviceToken/);
|
|
39
42
|
});
|
|
40
43
|
|
|
@@ -59,21 +62,76 @@ test("workspace user administration example takes workspaces-core's workspace CR
|
|
|
59
62
|
assert.equal(packageManifest.name, "@app/users-workspace");
|
|
60
63
|
assert.equal(packageManifest.jskit?.mutations, undefined);
|
|
61
64
|
assert.deepEqual(packageManifest.jskit?.capabilities?.provides, ["app.users-workspace"]);
|
|
62
|
-
assert.match(feature, /
|
|
65
|
+
assert.match(feature, /ownerRepository: "users\.profiles"/);
|
|
66
|
+
assert.match(feature, /visibility: "workspace"/);
|
|
63
67
|
assert.match(feature, /import \{ WORKSPACE_CRUD_SCOPE \} from "@jskit-ai\/workspaces-core\/server\/support\/workspaceCrud";/);
|
|
64
68
|
assert.match(feature, /scope: WORKSPACE_CRUD_SCOPE/);
|
|
65
69
|
assert.doesNotMatch(feature, /\.make\(|\.singleton\(|containerToken|repositoryToken|serviceToken/);
|
|
66
70
|
});
|
|
67
71
|
|
|
68
|
-
test("both user administration variants stay read-only
|
|
72
|
+
test("both user administration variants stay read-only on users-core's one users table resource", async () => {
|
|
69
73
|
for (const packageName of ["users", "users-workspace"]) {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
).href);
|
|
73
|
-
const
|
|
74
|
+
const packageRootPath = path.join(patternRoot, "example", "packages", packageName);
|
|
75
|
+
const crudModulePath = path.join(packageRootPath, "src", "shared", "userCrud.js");
|
|
76
|
+
const crudModule = await import(pathToFileURL(crudModulePath).href);
|
|
77
|
+
const { userCrud } = crudModule;
|
|
78
|
+
const manifest = JSON.parse(await readFile(path.join(packageRootPath, "package.json"), "utf8"));
|
|
74
79
|
|
|
75
|
-
assert.deepEqual(Object.keys(
|
|
76
|
-
assert.equal(
|
|
77
|
-
assert.equal(
|
|
80
|
+
assert.deepEqual(Object.keys(crudModule), ["userCrud"]);
|
|
81
|
+
assert.equal(userCrud.resource, userProfileTableResource);
|
|
82
|
+
assert.equal(userCrud.namespace, "users");
|
|
83
|
+
assert.deepEqual(Object.keys(userCrud.operations), ["list", "view"]);
|
|
84
|
+
assert.equal(Object.hasOwn(userCrud.operations, "create"), false);
|
|
85
|
+
assert.deepEqual(
|
|
86
|
+
Object.keys(userCrud.operations.view.output.schema.getFieldDefinitions()).sort(),
|
|
87
|
+
["createdAt", "displayName", "email", "id", "updatedAt", "username"]
|
|
88
|
+
);
|
|
89
|
+
assert.doesNotMatch(await readFile(crudModulePath, "utf8"), /defineTableResource/);
|
|
90
|
+
assert.ok(manifest.jskit.capabilities.requires.includes("users.profiles"));
|
|
91
|
+
assert.equal(manifest.dependencies["@jskit-ai/users-core"], packageJson.version);
|
|
78
92
|
}
|
|
79
93
|
});
|
|
94
|
+
|
|
95
|
+
test("the workspace variant lists and shows only the caller's workspace's active members", async () => {
|
|
96
|
+
const { workspaceMembersOnly } = await import(pathToFileURL(path.join(
|
|
97
|
+
patternRoot, "example", "packages", "users-workspace", "src", "server", "workspaceMembersOnly.js"
|
|
98
|
+
)).href);
|
|
99
|
+
const calls = [];
|
|
100
|
+
const repository = {
|
|
101
|
+
query: async (params) => (calls.push(["query", params.filters]), { data: [] }),
|
|
102
|
+
get: async (id) => (calls.push(["get", id]), { data: { id } }),
|
|
103
|
+
pageLimits: () => ({}),
|
|
104
|
+
// users.profiles' other methods read and write every user.
|
|
105
|
+
findByEmail: async () => ({ id: "3" }),
|
|
106
|
+
countUsers: async () => 3,
|
|
107
|
+
upsert: async () => ({ id: "3" })
|
|
108
|
+
};
|
|
109
|
+
const memberCalls = [];
|
|
110
|
+
const memberships = {
|
|
111
|
+
activeMemberIds: async (workspaceId, callOptions) => (memberCalls.push(callOptions), workspaceId === "7" ? ["1", "2"] : [])
|
|
112
|
+
};
|
|
113
|
+
const users = workspaceMembersOnly(repository, memberships);
|
|
114
|
+
const options = { context: { workspace: { id: "7" } } };
|
|
115
|
+
|
|
116
|
+
await users.query({ filters: { q: "ann" }, page: { size: 20 } }, options);
|
|
117
|
+
await users.query({ filters: { id: ["2", "3"] } }, options);
|
|
118
|
+
await users.query({ filters: { id: "3" } }, options);
|
|
119
|
+
await users.query({}, { context: { workspace: { id: "8" } } });
|
|
120
|
+
assert.deepEqual(calls.splice(0), [
|
|
121
|
+
["query", { q: "ann", id: ["1", "2"] }],
|
|
122
|
+
["query", { id: ["2"] }],
|
|
123
|
+
["query", { id: [] }],
|
|
124
|
+
["query", { id: [] }]
|
|
125
|
+
]);
|
|
126
|
+
assert.deepEqual(await users.get("1", {}, options), { data: { id: "1" } });
|
|
127
|
+
assert.equal(await users.get("3", {}, { ...options, missing: "skip" }), null);
|
|
128
|
+
await assert.rejects(users.get("3", {}, options), (error) => error.status === 404 && error.code === "crud.document.notFound");
|
|
129
|
+
assert.deepEqual(calls, [["get", "1"]]);
|
|
130
|
+
assert.equal(users.pageLimits, repository.pageLimits);
|
|
131
|
+
// Only the narrowed reads pass through: nothing else of users.profiles reaches users past the workspace.
|
|
132
|
+
assert.deepEqual(Object.keys(users).sort(), ["get", "pageLimits", "query"]);
|
|
133
|
+
// The memberships read gets only the context and transaction, never the list's own settings.
|
|
134
|
+
const trx = { id: "trx" };
|
|
135
|
+
await users.query({}, { ...options, trx, format: "jsonapi", missing: "skip" });
|
|
136
|
+
assert.deepEqual(memberCalls.at(-1), { context: options.context, trx });
|
|
137
|
+
});
|
|
@@ -3,7 +3,7 @@ import test from "node:test";
|
|
|
3
3
|
import { readSingleMultipartFile } from "@jskit-ai/uploads-runtime/server/multipart/readSingleMultipartFile";
|
|
4
4
|
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
5
5
|
import { validateOperationSection } from "../../http-runtime/src/shared/validators/operationValidation.js";
|
|
6
|
-
import {
|
|
6
|
+
import { userProfileContract } from "../src/shared/resources/userProfileResource.js";
|
|
7
7
|
import { registerAccountProfileRoutes } from "../src/server/accountProfile/accountProfileRoutes.js";
|
|
8
8
|
import { registerAccountPreferencesRoutes } from "../src/server/accountPreferences/accountPreferencesRoutes.js";
|
|
9
9
|
import { registerAccountNotificationsRoutes } from "../src/server/accountNotifications/accountNotificationsRoutes.js";
|
|
@@ -319,7 +319,7 @@ test("account settings jsonapi transport resolves response resource id from requ
|
|
|
319
319
|
|
|
320
320
|
test("avatar upload operation accepts the internal multipart stream field", () => {
|
|
321
321
|
const parsed = validateOperationSection({
|
|
322
|
-
operation:
|
|
322
|
+
operation: userProfileContract.operations.avatarUpload,
|
|
323
323
|
section: "body",
|
|
324
324
|
value: {
|
|
325
325
|
stream: {},
|
|
@@ -5,26 +5,24 @@ import { existsSync } from "node:fs";
|
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { deriveResourceRequiredMetadata } from "@jskit-ai/kernel/_testable";
|
|
7
7
|
import { resolveSchemaTransportSchemaDefinition } from "@jskit-ai/kernel/shared/validators";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { userProfileContract, userProfileCrud } from "../src/shared/resources/userProfileResource.js";
|
|
9
|
+
import { userSettingsContract, userSettingsCrud } from "../src/shared/resources/userSettingsResource.js";
|
|
10
10
|
|
|
11
|
-
function
|
|
12
|
-
assert.ok(
|
|
13
|
-
assert.equal(typeof
|
|
14
|
-
assert.equal(typeof
|
|
11
|
+
function assertContractShape(contract, label) {
|
|
12
|
+
assert.ok(contract, `${label} contract must exist.`);
|
|
13
|
+
assert.equal(typeof contract, "object", `${label} contract must be an object.`);
|
|
14
|
+
assert.equal(typeof contract.namespace, "string", `.namespace must be a string.`);
|
|
15
15
|
|
|
16
|
-
for (const operationName
|
|
17
|
-
const operation = resource.operations?.[operationName];
|
|
18
|
-
assert.equal(typeof operation, "object", `${label}.operations.${operationName} must exist.`);
|
|
16
|
+
for (const [operationName, operation] of Object.entries(contract.operations)) {
|
|
19
17
|
assert.equal(typeof operation.method, "string", `${label}.operations.${operationName}.method must exist.`);
|
|
20
18
|
const resolvedMessages =
|
|
21
19
|
operation?.messages && typeof operation.messages === "object"
|
|
22
20
|
? operation.messages
|
|
23
|
-
:
|
|
21
|
+
: contract?.messages;
|
|
24
22
|
assert.equal(
|
|
25
23
|
typeof resolvedMessages,
|
|
26
24
|
"object",
|
|
27
|
-
`${label}.operations.${operationName} must resolve messages from operation.messages or
|
|
25
|
+
`${label}.operations.${operationName} must resolve messages from operation.messages or contract.messages.`
|
|
28
26
|
);
|
|
29
27
|
assert.equal(
|
|
30
28
|
typeof resolveSchemaTransportSchemaDefinition(operation.output, {
|
|
@@ -34,38 +32,84 @@ function assertResourceShape(resource, label) {
|
|
|
34
32
|
"object",
|
|
35
33
|
`${label}.operations.${operationName} payload schema is required.`
|
|
36
34
|
);
|
|
35
|
+
if (operation.body) {
|
|
36
|
+
assert.equal(typeof operation.body.schema, "object", `${label}.operations.${operationName}.body.schema is required.`);
|
|
37
|
+
}
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
-
assert.equal(typeof resource.operations.replace.body?.schema, "object", `${label}.operations.replace.body.schema is required.`);
|
|
41
|
-
assert.equal(typeof resource.operations.patch.body?.schema, "object", `${label}.operations.patch.body.schema is required.`);
|
|
42
|
-
|
|
43
|
-
const requiredMetadata = deriveResourceRequiredMetadata(resource);
|
|
40
|
+
const requiredMetadata = deriveResourceRequiredMetadata(contract);
|
|
44
41
|
assert.ok(Array.isArray(requiredMetadata.create), `${label}.derivedRequired.create must be an array.`);
|
|
45
42
|
assert.ok(Array.isArray(requiredMetadata.replace), `${label}.derivedRequired.replace must be an array.`);
|
|
46
43
|
assert.ok(Array.isArray(requiredMetadata.patch), `${label}.derivedRequired.patch must be an array.`);
|
|
47
44
|
}
|
|
48
45
|
|
|
49
|
-
test("
|
|
50
|
-
const
|
|
51
|
-
userProfile:
|
|
52
|
-
userSettings:
|
|
46
|
+
test("account API contracts expose canonical validators for the operations they serve", () => {
|
|
47
|
+
const contractsByLabel = {
|
|
48
|
+
userProfile: userProfileContract,
|
|
49
|
+
userSettings: userSettingsContract
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
for (const [label, contract] of Object.entries(contractsByLabel)) {
|
|
53
|
+
assertContractShape(contract, label);
|
|
54
|
+
}
|
|
55
|
+
assert.deepEqual(Object.keys(userProfileContract.operations), ["patch", "avatarUpload", "avatarDelete"]);
|
|
56
|
+
assert.deepEqual(Object.keys(userSettingsContract.operations), [
|
|
57
|
+
"view",
|
|
58
|
+
"preferencesUpdate",
|
|
59
|
+
"notificationsUpdate",
|
|
60
|
+
"passwordChange",
|
|
61
|
+
"passwordMethodToggle",
|
|
62
|
+
"oauthLinkStart",
|
|
63
|
+
"oauthUnlink",
|
|
64
|
+
"logoutOtherSessions"
|
|
65
|
+
]);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("account CRUD contracts keep their create, replace and patch bodies and their outputs", () => {
|
|
69
|
+
const contractsByLabel = {
|
|
70
|
+
userProfile: userProfileCrud,
|
|
71
|
+
userSettings: userSettingsCrud
|
|
53
72
|
};
|
|
54
73
|
|
|
55
|
-
for (const [label,
|
|
56
|
-
|
|
74
|
+
for (const [label, contract] of Object.entries(contractsByLabel)) {
|
|
75
|
+
assertContractShape(contract, label);
|
|
76
|
+
assert.deepEqual(Object.keys(contract.operations), ["view", "list", "create", "replace", "patch"]);
|
|
77
|
+
assert.equal(contract.operations.view.method, "GET");
|
|
78
|
+
assert.equal(contract.operations.list.method, "GET");
|
|
79
|
+
assert.equal(contract.operations.create.method, "POST");
|
|
80
|
+
assert.equal(contract.operations.replace.method, "PUT");
|
|
81
|
+
assert.equal(contract.operations.patch.method, "PATCH");
|
|
82
|
+
assert.equal(contract.operations.create.body.mode, "create");
|
|
83
|
+
assert.equal(contract.operations.replace.body.mode, "replace");
|
|
84
|
+
assert.equal(contract.operations.patch.body.mode, "patch");
|
|
85
|
+
assert.deepEqual(contract.operations.list.realtime.events, [`${label.toLowerCase()}.record.changed`]);
|
|
57
86
|
}
|
|
87
|
+
assert.deepEqual(Object.keys(userProfileCrud.operations.patch.body.schema.getFieldDefinitions()), ["displayName"]);
|
|
88
|
+
assert.deepEqual(Object.keys(userSettingsCrud.operations.patch.body.schema.getFieldDefinitions()), [
|
|
89
|
+
"theme",
|
|
90
|
+
"locale",
|
|
91
|
+
"timeZone",
|
|
92
|
+
"dateFormat",
|
|
93
|
+
"numberFormat",
|
|
94
|
+
"currencyCode",
|
|
95
|
+
"avatarSize",
|
|
96
|
+
"productUpdates",
|
|
97
|
+
"accountActivity",
|
|
98
|
+
"securityAlerts"
|
|
99
|
+
]);
|
|
100
|
+
assert.equal(userSettingsCrud.operations.view.output.schema, userSettingsContract.operations.view.output.schema);
|
|
101
|
+
assert.equal(userProfileCrud.operations.patch.body.schema, userProfileContract.operations.patch.body.schema);
|
|
58
102
|
});
|
|
59
103
|
|
|
60
104
|
test("specialized settings and invite operations expose canonical validators", () => {
|
|
61
105
|
const operationSpecs = [
|
|
62
|
-
{ label: "userProfile.avatarUpload", operation:
|
|
63
|
-
{ label: "userProfile.avatarDelete", operation:
|
|
64
|
-
{ label: "userSettings.passwordChange", operation:
|
|
65
|
-
{ label: "userSettings.passwordMethodToggle", operation:
|
|
66
|
-
{ label: "userSettings.oauthLinkStart", operation:
|
|
67
|
-
{ label: "userSettings.oauthUnlink", operation:
|
|
68
|
-
{ label: "userSettings.logoutOtherSessions", operation:
|
|
106
|
+
{ label: "userProfile.avatarUpload", operation: userProfileContract.operations.avatarUpload },
|
|
107
|
+
{ label: "userProfile.avatarDelete", operation: userProfileContract.operations.avatarDelete },
|
|
108
|
+
{ label: "userSettings.passwordChange", operation: userSettingsContract.operations.passwordChange },
|
|
109
|
+
{ label: "userSettings.passwordMethodToggle", operation: userSettingsContract.operations.passwordMethodToggle },
|
|
110
|
+
{ label: "userSettings.oauthLinkStart", operation: userSettingsContract.operations.oauthLinkStart },
|
|
111
|
+
{ label: "userSettings.oauthUnlink", operation: userSettingsContract.operations.oauthUnlink },
|
|
112
|
+
{ label: "userSettings.logoutOtherSessions", operation: userSettingsContract.operations.logoutOtherSessions }
|
|
69
113
|
];
|
|
70
114
|
|
|
71
115
|
for (const { label, operation } of operationSpecs) {
|
package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
|
|
2
|
-
|
|
3
|
-
const resource = defineCrudResource({
|
|
4
|
-
namespace: "users",
|
|
5
|
-
tableName: "users",
|
|
6
|
-
crudOperations: ["list", "view"],
|
|
7
|
-
schema: {
|
|
8
|
-
name: {
|
|
9
|
-
type: "string",
|
|
10
|
-
required: true,
|
|
11
|
-
minLength: 1,
|
|
12
|
-
maxLength: 160,
|
|
13
|
-
actualField: "display_name",
|
|
14
|
-
search: true,
|
|
15
|
-
operations: {
|
|
16
|
-
output: { required: false }
|
|
17
|
-
}
|
|
18
|
-
},
|
|
19
|
-
email: {
|
|
20
|
-
type: "string",
|
|
21
|
-
required: true,
|
|
22
|
-
search: true,
|
|
23
|
-
operations: {
|
|
24
|
-
output: { required: false }
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
username: {
|
|
28
|
-
type: "string",
|
|
29
|
-
required: true,
|
|
30
|
-
search: true,
|
|
31
|
-
operations: {
|
|
32
|
-
output: { required: false }
|
|
33
|
-
}
|
|
34
|
-
},
|
|
35
|
-
createdAt: {
|
|
36
|
-
type: "dateTime",
|
|
37
|
-
required: true,
|
|
38
|
-
storage: { writeSerializer: "datetime-utc" },
|
|
39
|
-
operations: {
|
|
40
|
-
output: { required: true }
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
updatedAt: {
|
|
44
|
-
type: "dateTime",
|
|
45
|
-
required: true,
|
|
46
|
-
storage: { writeSerializer: "datetime-utc" },
|
|
47
|
-
operations: {
|
|
48
|
-
output: { required: true }
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
},
|
|
52
|
-
searchSchema: {
|
|
53
|
-
id: {
|
|
54
|
-
type: "id",
|
|
55
|
-
actualField: "id"
|
|
56
|
-
},
|
|
57
|
-
q: {
|
|
58
|
-
type: "string",
|
|
59
|
-
oneOf: ["name", "email", "username"],
|
|
60
|
-
filterOperator: "like",
|
|
61
|
-
splitBy: " ",
|
|
62
|
-
matchAll: true
|
|
63
|
-
}
|
|
64
|
-
},
|
|
65
|
-
defaultSort: ["name", "email"],
|
|
66
|
-
autofilter: "public"
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
export { resource };
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
|
|
2
|
-
|
|
3
|
-
const resource = defineCrudResource({
|
|
4
|
-
namespace: "users",
|
|
5
|
-
tableName: "users",
|
|
6
|
-
crudOperations: ["list", "view"],
|
|
7
|
-
schema: {
|
|
8
|
-
name: {
|
|
9
|
-
type: "string",
|
|
10
|
-
required: true,
|
|
11
|
-
minLength: 1,
|
|
12
|
-
maxLength: 160,
|
|
13
|
-
actualField: "display_name",
|
|
14
|
-
search: true,
|
|
15
|
-
operations: { output: { required: false } }
|
|
16
|
-
},
|
|
17
|
-
email: {
|
|
18
|
-
type: "string",
|
|
19
|
-
required: true,
|
|
20
|
-
search: true,
|
|
21
|
-
operations: { output: { required: false } }
|
|
22
|
-
},
|
|
23
|
-
username: {
|
|
24
|
-
type: "string",
|
|
25
|
-
required: true,
|
|
26
|
-
search: true,
|
|
27
|
-
operations: { output: { required: false } }
|
|
28
|
-
},
|
|
29
|
-
createdAt: {
|
|
30
|
-
type: "dateTime",
|
|
31
|
-
required: true,
|
|
32
|
-
storage: { writeSerializer: "datetime-utc" },
|
|
33
|
-
operations: { output: { required: true } }
|
|
34
|
-
},
|
|
35
|
-
updatedAt: {
|
|
36
|
-
type: "dateTime",
|
|
37
|
-
required: true,
|
|
38
|
-
storage: { writeSerializer: "datetime-utc" },
|
|
39
|
-
operations: { output: { required: true } }
|
|
40
|
-
}
|
|
41
|
-
},
|
|
42
|
-
searchSchema: {
|
|
43
|
-
id: { type: "id", actualField: "id" },
|
|
44
|
-
q: {
|
|
45
|
-
type: "string",
|
|
46
|
-
oneOf: ["name", "email", "username"],
|
|
47
|
-
filterOperator: "like",
|
|
48
|
-
splitBy: " ",
|
|
49
|
-
matchAll: true
|
|
50
|
-
}
|
|
51
|
-
},
|
|
52
|
-
defaultSort: ["name", "email"],
|
|
53
|
-
autofilter: "public"
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
export { resource };
|