feat: init
This commit is contained in:
@@ -0,0 +1,351 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { Api } from "../utils.api";
|
||||
import Application, {
|
||||
PublicApplicationObject,
|
||||
} from "../../../src/services/applications/entities/application";
|
||||
import { cloneDeep } from "lodash";
|
||||
|
||||
import { logger as log } from "../../../src/core/platform/framework";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
describe("Applications", () => {
|
||||
const url = "/internal/services/applications/v1";
|
||||
|
||||
let platform: TestPlatform;
|
||||
let testDbService: TestDbService;
|
||||
let api: Api;
|
||||
let appRepo;
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init();
|
||||
await platform.database.getConnector().drop();
|
||||
testDbService = await TestDbService.getInstance(platform, true);
|
||||
await testDbService.createDefault();
|
||||
postPayload.company_id = platform.workspace.company_id;
|
||||
api = new Api(platform);
|
||||
appRepo = await testDbService.getRepository("application", Application);
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(done => {
|
||||
platform.tearDown().then(() => done());
|
||||
});
|
||||
|
||||
const publishApp = async id => {
|
||||
const entity = await appRepo.findOne({ id });
|
||||
if (!entity) throw new Error(`entity ${id} not found`);
|
||||
entity.publication.published = true;
|
||||
await appRepo.save(entity);
|
||||
};
|
||||
|
||||
describe("Create application", function () {
|
||||
it("should 403 if creator is not a company admin", async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
|
||||
const response = await api.post(`${url}/applications`, payload, user.id);
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 on application create", async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
const response = await api.post(`${url}/applications`, payload);
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const r = response.resource;
|
||||
|
||||
expect(r.company_id).toBe(payload.resource.company_id);
|
||||
expect(!!r.is_default).toBe(false);
|
||||
expect(r.identity).toMatchObject(payload.resource.identity);
|
||||
expect(r.access).toMatchObject(payload.resource.access);
|
||||
expect(r.display).toMatchObject(payload.resource.display);
|
||||
expect(r.publication).toMatchObject(payload.resource.publication);
|
||||
expect(r.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
updated_at: expect.any(Number),
|
||||
version: 0,
|
||||
});
|
||||
|
||||
expect(r.api).toMatchObject({
|
||||
hooks_url: payload.resource.api.hooks_url,
|
||||
allowed_ips: payload.resource.api.allowed_ips,
|
||||
private_key: expect.any(String),
|
||||
});
|
||||
|
||||
expect(r.api.private_key).not.toBe("");
|
||||
|
||||
const dbData = await appRepo.findOne({ id: response.resource.id });
|
||||
|
||||
expect(dbData.api).toMatchObject({
|
||||
allowed_ips: payload.resource.api.allowed_ips,
|
||||
hooks_url: payload.resource.api.hooks_url,
|
||||
private_key: expect.any(String),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Update application", function () {
|
||||
let createdApp: PublicApplicationObject;
|
||||
|
||||
beforeAll(async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
const response = await api.post(`${url}/applications`, payload);
|
||||
createdApp = response.resource;
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 if editor is not a company admin", async done => {
|
||||
if (!createdApp) throw new Error("can't find created app");
|
||||
log.debug(createdApp);
|
||||
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
|
||||
const response = await api.post(`${url}/applications/${createdApp.id}`, postPayload, user.id);
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 if application not found", async done => {
|
||||
const response = await api.post(`${url}/applications/${uuidv1()}`, { resource: postPayload });
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
describe("Unpublished application", () => {
|
||||
it("should 200 on application update", async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
|
||||
payload.resource.is_default = true;
|
||||
payload.resource.identity.name = "test2";
|
||||
payload.resource.api.hooks_url = "123123";
|
||||
payload.resource.access.read = [];
|
||||
payload.resource.publication.requested = true;
|
||||
|
||||
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const r = response.resource;
|
||||
|
||||
expect(r.company_id).toBe(payload.resource.company_id);
|
||||
expect(!!r.is_default).toBe(false);
|
||||
expect(r.identity).toMatchObject(payload.resource.identity);
|
||||
|
||||
expect(r.access).toMatchObject(payload.resource.access);
|
||||
expect(r.display).toMatchObject(payload.resource.display);
|
||||
expect(r.publication).toMatchObject(payload.resource.publication);
|
||||
expect(r.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
updated_at: expect.any(Number),
|
||||
version: 1,
|
||||
});
|
||||
|
||||
expect(r.api).toBeTruthy();
|
||||
|
||||
const dbData = await appRepo.findOne({ id: response.resource.id });
|
||||
|
||||
expect(dbData.api).toMatchObject({
|
||||
allowed_ips: payload.resource.api.allowed_ips,
|
||||
hooks_url: payload.resource.api.hooks_url,
|
||||
private_key: expect.any(String),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe.skip("Published application", () => {
|
||||
beforeAll(async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
const response = await api.post(`${url}/applications`, payload);
|
||||
createdApp = response.resource;
|
||||
await publishApp(createdApp.id);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 on update if allowed fields changed", async done => {
|
||||
const payload = { resource: cloneDeep(createdApp) as Application };
|
||||
const entity = await appRepo.findOne({ id: createdApp.id });
|
||||
payload.resource.api = cloneDeep(entity.api);
|
||||
payload.resource.publication.requested = true;
|
||||
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(response.resource.publication).toMatchObject({
|
||||
requested: true,
|
||||
published: true,
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 400 on update if not allowed fields changed", async done => {
|
||||
const payload = { resource: cloneDeep(createdApp) as Application };
|
||||
const entity = await appRepo.findOne({ id: createdApp.id });
|
||||
payload.resource.api = cloneDeep(entity.api);
|
||||
const response = await api.post(`${url}/applications/${createdApp.id}`, payload);
|
||||
expect(response.statusCode).toBe(400);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("Get applications", function () {
|
||||
let firstApp: PublicApplicationObject;
|
||||
let secondApp: PublicApplicationObject;
|
||||
let thirdApp: PublicApplicationObject;
|
||||
beforeAll(async done => {
|
||||
const payload = { resource: cloneDeep(postPayload) };
|
||||
firstApp = (await api.post(`${url}/applications`, payload)).resource;
|
||||
secondApp = (await api.post(`${url}/applications`, payload)).resource;
|
||||
thirdApp = (await api.post(`${url}/applications`, payload)).resource;
|
||||
|
||||
await publishApp(firstApp.id);
|
||||
await publishApp(secondApp.id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should list published applications", async done => {
|
||||
const response = await api.get(`${url}/applications`);
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const published = response.resources.filter(a => a.publication.published).length;
|
||||
const unpublished = response.resources.filter(a => a.publication.unpublished).length;
|
||||
|
||||
expect(published).toBeGreaterThanOrEqual(2);
|
||||
expect(unpublished).toEqual(0);
|
||||
|
||||
expect(response.resources.map(a => a.id)).toEqual(
|
||||
expect.arrayContaining([firstApp.id, secondApp.id]),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return public object for published application to any user", async done => {
|
||||
const response = await api.get(`${url}/applications/${firstApp.id}`, uuidv1());
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.resource.id).toEqual(firstApp.id);
|
||||
expect(response.resource.api).toBeFalsy();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return public object for unpublished application to any user", async done => {
|
||||
const response = await api.get(`${url}/applications/${thirdApp.id}`, uuidv1());
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.resource.id).toEqual(thirdApp.id);
|
||||
expect(response.resource.api).toBeFalsy();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return whole object for published application to admin", async done => {
|
||||
const response = await api.get(`${url}/applications/${firstApp.id}`);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.resource.id).toEqual(firstApp.id);
|
||||
expect(response.resource.api).toBeTruthy();
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return whole object for unpublished application to admin", async done => {
|
||||
const response = await api.get(`${url}/applications/${thirdApp.id}`);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.resource.id).toEqual(thirdApp.id);
|
||||
expect(response.resource.api).toBeTruthy();
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const postPayload = {
|
||||
is_default: true,
|
||||
company_id: null,
|
||||
identity: {
|
||||
code: "code",
|
||||
name: "name",
|
||||
icon: "icon",
|
||||
description: "description",
|
||||
website: "website",
|
||||
categories: [],
|
||||
compatibility: [],
|
||||
},
|
||||
api: {
|
||||
hooks_url: "hooks_url",
|
||||
allowed_ips: "allowed_ips",
|
||||
},
|
||||
access: {
|
||||
read: ["messages"],
|
||||
write: ["messages"],
|
||||
delete: ["messages"],
|
||||
hooks: ["messages"],
|
||||
},
|
||||
display: {
|
||||
twake: {
|
||||
version: 1,
|
||||
|
||||
files: {
|
||||
editor: {
|
||||
preview_url: "string", //Open a preview inline (iframe)
|
||||
edition_url: "string", //Url to edit the file (full screen)
|
||||
extensions: [], //Main extensions app can read
|
||||
// if file was created by the app, then the app is able to edit with or without extension
|
||||
empty_files: [
|
||||
{
|
||||
url: "string", // "https://[...]/empty.docx";
|
||||
filename: "string", // "Untitled.docx";
|
||||
name: "string", // "Word Document";
|
||||
},
|
||||
],
|
||||
},
|
||||
actions: [
|
||||
//List of action that can apply on a file
|
||||
{
|
||||
name: "string",
|
||||
id: "string",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
//Chat plugin
|
||||
chat: {
|
||||
input: true,
|
||||
commands: [
|
||||
{
|
||||
command: "string", // my_app mycommand
|
||||
description: "string",
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
//List of action that can apply on a message
|
||||
{
|
||||
name: "string",
|
||||
id: "string",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
//Allow app to appear as a bot user in direct chat
|
||||
direct: false,
|
||||
|
||||
//Display app as a standalone application in a tab
|
||||
tab: { url: "string" },
|
||||
|
||||
//Display app as a standalone application on the left bar
|
||||
standalone: { url: "string" },
|
||||
|
||||
//Define where the app can be configured from
|
||||
configuration: ["global", "channel"],
|
||||
},
|
||||
},
|
||||
publication: {
|
||||
requested: false, //Publication requested
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
import * as crypto from "crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { FastifyInstance, FastifyPluginCallback, FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { Api } from "../utils.api";
|
||||
|
||||
import { logger as log } from "../../../src/core/platform/framework";
|
||||
|
||||
let signingSecret = "";
|
||||
|
||||
describe("Application events", () => {
|
||||
const url = "/internal/services/applications/v1";
|
||||
let platform: TestPlatform;
|
||||
let api: Api;
|
||||
let appId: string;
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init(undefined, testAppHookRoute);
|
||||
|
||||
await platform.database.getConnector().drop();
|
||||
|
||||
await TestDbService.getInstance(platform, true);
|
||||
api = new Api(platform);
|
||||
|
||||
postPayload.company_id = platform.workspace.company_id;
|
||||
|
||||
const createdApplication = await api.post("/internal/services/applications/v1/applications", {
|
||||
resource: postPayload,
|
||||
});
|
||||
|
||||
appId = createdApplication.resource.id;
|
||||
signingSecret = createdApplication.resource.api.private_key;
|
||||
|
||||
ends();
|
||||
|
||||
afterAll(done => {
|
||||
platform.tearDown().then(() => done());
|
||||
});
|
||||
});
|
||||
|
||||
it("Should 200 on sending well formed event", async done => {
|
||||
const payload = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
type: "some type",
|
||||
name: "name",
|
||||
content: {},
|
||||
};
|
||||
|
||||
const response = await api.post(`${url}/applications/${appId}/event`, payload);
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.resource).toMatchObject({ a: "b" });
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
const postPayload = {
|
||||
is_default: false,
|
||||
company_id: null,
|
||||
identity: {
|
||||
code: "code",
|
||||
name: "name",
|
||||
icon: "icon",
|
||||
description: "description",
|
||||
website: "website",
|
||||
categories: [],
|
||||
compatibility: [],
|
||||
},
|
||||
api: {
|
||||
hooks_url: "http://localhost:3000/test/appHook",
|
||||
allowed_ips: "allowed_ips",
|
||||
},
|
||||
access: {
|
||||
read: ["messages"],
|
||||
write: ["messages"],
|
||||
delete: ["messages"],
|
||||
hooks: ["messages"],
|
||||
},
|
||||
display: {},
|
||||
publication: {
|
||||
requested: true,
|
||||
},
|
||||
};
|
||||
|
||||
const testAppHookRoute = (fastify: FastifyInstance) => {
|
||||
const routes: FastifyPluginCallback = (fastify: FastifyInstance, options, next) => {
|
||||
fastify.route({
|
||||
method: "POST",
|
||||
url: "/test/appHook",
|
||||
handler: (request: FastifyRequest, reply: FastifyReply): Promise<any> => {
|
||||
const signature = request.headers["x-twake-signature"];
|
||||
if (!signature) {
|
||||
reply.status(403);
|
||||
reply.send({ error: "Signature is missing" });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", signingSecret)
|
||||
.update(JSON.stringify(request.body))
|
||||
.digest("hex");
|
||||
if (expectedSignature != signature) {
|
||||
reply.status(403);
|
||||
reply.send({ error: "Wrong signature" });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
log.debug({ signatureMatched: expectedSignature == signature });
|
||||
return Promise.resolve({ a: "b" });
|
||||
},
|
||||
});
|
||||
|
||||
next();
|
||||
};
|
||||
fastify.register(routes);
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { Api } from "../utils.api";
|
||||
import { logger as log } from "../../../src/core/platform/framework";
|
||||
import { ApplicationLoginResponse } from "../../../src/services/applicationsapi/web/types";
|
||||
|
||||
describe("Applications", () => {
|
||||
let platform: TestPlatform;
|
||||
let testDbService: TestDbService;
|
||||
let api: Api;
|
||||
let appId: string;
|
||||
let private_key: string;
|
||||
let accessToken: ApplicationLoginResponse["access_token"];
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init();
|
||||
await platform.database.getConnector().drop();
|
||||
testDbService = await TestDbService.getInstance(platform, true);
|
||||
api = new Api(platform);
|
||||
|
||||
postPayload.company_id = platform.workspace.company_id;
|
||||
|
||||
const createdApplication = await api.post("/internal/services/applications/v1/applications", {
|
||||
resource: postPayload,
|
||||
});
|
||||
|
||||
appId = createdApplication.resource.id;
|
||||
private_key = createdApplication.resource.api.private_key;
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(done => {
|
||||
platform.tearDown().then(() => done());
|
||||
});
|
||||
|
||||
describe("Login", function () {
|
||||
it("Should be ok on valid token", async done => {
|
||||
expect(appId).toBeTruthy();
|
||||
|
||||
const response = await api.post("/api/console/v1/login", {
|
||||
id: appId,
|
||||
secret: private_key,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = (await response.json()).resource as ApplicationLoginResponse;
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
access_token: {
|
||||
time: expect.any(Number),
|
||||
expiration: expect.any(Number),
|
||||
refresh_expiration: expect.any(Number),
|
||||
value: expect.any(String),
|
||||
refresh: expect.any(String),
|
||||
type: expect.any(String),
|
||||
},
|
||||
});
|
||||
|
||||
accessToken = resource.access_token;
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get myself", function () {
|
||||
it("Should be 401 on invalid token", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/console/v1/me",
|
||||
headers: {
|
||||
authorization: `Bearer ${accessToken.value + "!!"}`,
|
||||
},
|
||||
});
|
||||
log.debug(response.json());
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("Should be 403 on auth by users (not company) token", async done => {
|
||||
const userToken = await platform.auth.getJWTToken();
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/console/v1/me",
|
||||
headers: {
|
||||
authorization: `Bearer ${userToken}`,
|
||||
},
|
||||
});
|
||||
log.debug(response.json());
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("Should be ok on valid token", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/console/v1/me",
|
||||
headers: {
|
||||
authorization: `Bearer ${accessToken.value}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const resource = (await response.json()).resource;
|
||||
log.debug(resource);
|
||||
expect(resource).toMatchObject(postPayload);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const postPayload = {
|
||||
is_default: false,
|
||||
company_id: null,
|
||||
identity: {
|
||||
code: "code",
|
||||
name: "name",
|
||||
icon: "icon",
|
||||
description: "description",
|
||||
website: "website",
|
||||
categories: [],
|
||||
compatibility: [],
|
||||
},
|
||||
api: {
|
||||
hooks_url: "hooks_url",
|
||||
allowed_ips: "allowed_ips",
|
||||
},
|
||||
access: {
|
||||
read: ["messages"],
|
||||
write: ["messages"],
|
||||
delete: ["messages"],
|
||||
hooks: ["messages"],
|
||||
},
|
||||
display: {},
|
||||
publication: {
|
||||
requested: true,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,176 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { ObjectId } from "mongodb";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import io from "socket.io-client";
|
||||
import { Channel } from "../../../src/services/channels/entities/channel";
|
||||
import {
|
||||
getChannelPath,
|
||||
getPublicRoomName,
|
||||
} from "../../../src/services/channels/services/channel/realtime";
|
||||
import { WorkspaceExecutionContext } from "../../../src/services/channels/types";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ChannelUtils, get as getChannelUtils } from "./utils";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The Channels Realtime feature", () => {
|
||||
const url = "/internal/services/channels/v1";
|
||||
let platform: TestPlatform;
|
||||
let socket: SocketIOClient.Socket;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"websocket",
|
||||
"applications",
|
||||
"webserver",
|
||||
"channels",
|
||||
"auth",
|
||||
"search",
|
||||
"realtime",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
socket && socket.close();
|
||||
socket = null;
|
||||
});
|
||||
|
||||
function connect() {
|
||||
socket = io.connect("http://localhost:3000", { path: "/socket" });
|
||||
socket.connect();
|
||||
}
|
||||
|
||||
describe("On channel creation", () => {
|
||||
it("should notify the client", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
const channelName = new ObjectId().toString();
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", {
|
||||
name: getPublicRoomName(platform.workspace),
|
||||
token: roomToken,
|
||||
});
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
name: channelName,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(201);
|
||||
});
|
||||
socket.on(
|
||||
"realtime:resource",
|
||||
(event: { type: any; action: any; resource: { name: any } }) => {
|
||||
// we can also receive other types of events (channel_activity etc)
|
||||
if (event.type === "channel") {
|
||||
expect(event.type).toEqual("channel");
|
||||
expect(event.action).toEqual("saved");
|
||||
expect(event.resource.name).toEqual(channelName);
|
||||
done();
|
||||
}
|
||||
},
|
||||
);
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("On channel removal", () => {
|
||||
it("should notify the client", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
const channelName = new ObjectId().toString();
|
||||
|
||||
const channel = channelUtils.getChannel(platform.currentUser.id);
|
||||
channel.name = channelName;
|
||||
|
||||
const creationResult = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext({ id: channel.owner }),
|
||||
);
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.on(
|
||||
"realtime:resource",
|
||||
(event: { action: string; type: any; path: any; resource: { id: any } }) => {
|
||||
if (event.action !== "deleted" || event.type !== "channel") {
|
||||
// we can receive event when resource is created...
|
||||
// we can also receive other types of events (channel_activity etc)
|
||||
return;
|
||||
}
|
||||
|
||||
expect(event.type).toEqual("channel");
|
||||
expect(event.action).toEqual("deleted");
|
||||
expect(event.path).toEqual(
|
||||
getChannelPath(
|
||||
{ id: creationResult.entity.id } as Channel,
|
||||
{
|
||||
workspace: platform.workspace,
|
||||
} as WorkspaceExecutionContext,
|
||||
),
|
||||
);
|
||||
expect(event.resource.id).toEqual(creationResult.entity.id);
|
||||
done();
|
||||
},
|
||||
);
|
||||
socket.emit("realtime:join", {
|
||||
name: getPublicRoomName(platform.workspace),
|
||||
token: roomToken,
|
||||
});
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${creationResult.entity.company_id}/workspaces/${creationResult.entity.workspace_id}/channels/${creationResult.entity.id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,136 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ResourceGetResponse, ResourceListResponse, User } from "../../../src/utils/types";
|
||||
import { Channel } from "../../../src/services/channels/entities";
|
||||
import { ChannelVisibility, WorkspaceExecutionContext } from "../../../src/services/channels/types";
|
||||
import { ChannelMember } from "../../../src/services/channels/entities";
|
||||
import { ChannelUtils, get as getChannelUtils } from "./utils";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { ChannelObject } from "../../../src/services/channels/services/channel/types";
|
||||
import { Api } from "../utils.api";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The /internal/services/channels/v1 API", () => {
|
||||
const url = "/internal/services/channels/v1";
|
||||
let platform: TestPlatform;
|
||||
let channelUtils: ChannelUtils;
|
||||
let testDbService: TestDbService;
|
||||
let api: Api;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init();
|
||||
testDbService = new TestDbService(platform);
|
||||
api = new Api(platform);
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
});
|
||||
|
||||
async function testAccess(url, method, done) {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method,
|
||||
url,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
done();
|
||||
}
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new channel instance
|
||||
*
|
||||
* @param owner will be a random uuidv4 if not defined
|
||||
*/
|
||||
function getChannel(owner: string = uuidv1()): Channel {
|
||||
const channel = new Channel();
|
||||
|
||||
channel.name = "Test Channel";
|
||||
channel.company_id = platform.workspace.company_id;
|
||||
channel.workspace_id = platform.workspace.workspace_id;
|
||||
channel.is_default = false;
|
||||
channel.visibility = ChannelVisibility.PRIVATE;
|
||||
channel.archived = false;
|
||||
channel.owner = owner;
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
async function getChannelREST(channelId: string): Promise<ChannelObject> {
|
||||
const response = await api.get(
|
||||
`${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${channelId}`,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
|
||||
const channelGetResult: ResourceGetResponse<ChannelObject> = deserialize(
|
||||
ResourceGetResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
return channelGetResult.resource;
|
||||
}
|
||||
|
||||
describe("Channels search", () => {
|
||||
it("Should find channels by name", async done => {
|
||||
const ws0pk = { id: uuidv1(), company_id: platform.workspace.company_id };
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
const newUser = await testDbService.createUser([ws0pk]);
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const channel = getChannel();
|
||||
channel.name = `test channel ${i}`;
|
||||
await gr.services.channels.channels.save(channel, {}, getContext());
|
||||
|
||||
if (i == 0) continue;
|
||||
await gr.services.channels.members.save(
|
||||
{
|
||||
channel_id: channel.id,
|
||||
workspace_id: channel.workspace_id,
|
||||
company_id: channel.company_id,
|
||||
user_id: newUser.id,
|
||||
} as ChannelMember,
|
||||
channelUtils.getChannelContext(channel, platform.currentUser),
|
||||
);
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(() => r(true), 1000));
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: newUser.id });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/search`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
q: "test",
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(9);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,420 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import {
|
||||
ResourceCreateResponse,
|
||||
ResourceListResponse,
|
||||
User,
|
||||
Workspace,
|
||||
} from "../../../src/utils/types";
|
||||
import { Channel } from "../../../src/services/channels/entities";
|
||||
import { ChannelVisibility, WorkspaceExecutionContext } from "../../../src/services/channels/types";
|
||||
import { ChannelUtils, get as getChannelUtils } from "./utils";
|
||||
import { DirectChannel } from "../../../src/services/channels/entities/direct-channel";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The direct channels API", () => {
|
||||
const url = "/internal/services/channels/v1";
|
||||
let platform: TestPlatform;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"applications",
|
||||
"websocket",
|
||||
"channels",
|
||||
"auth",
|
||||
"storage",
|
||||
"counter",
|
||||
"statistics",
|
||||
],
|
||||
});
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
describe("Channel List - GET /channels", () => {
|
||||
it("should return empty list of direct channels", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(0);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return list of direct channels the user is member of", async done => {
|
||||
const channel = channelUtils.getChannel();
|
||||
const directChannelIn = channelUtils.getDirectChannel();
|
||||
const directChannelNotIn = channelUtils.getDirectChannel();
|
||||
const members = [platform.currentUser.id, uuidv1()];
|
||||
const directWorkspace: Workspace = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
};
|
||||
|
||||
const creationResult = await Promise.all([
|
||||
gr.services.channels.channels.save(channel, {}, getContext()),
|
||||
gr.services.channels.channels.save(
|
||||
directChannelIn,
|
||||
{
|
||||
members,
|
||||
},
|
||||
{ ...getContext(), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
gr.services.channels.channels.save(
|
||||
directChannelNotIn,
|
||||
{
|
||||
members: [uuidv1(), uuidv1()],
|
||||
},
|
||||
{ ...getContext({ id: uuidv1() }), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
]);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const directResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const directResult: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
directResponse.body,
|
||||
);
|
||||
|
||||
expect(directResponse.statusCode).toBe(200);
|
||||
expect(directResult.resources.length).toEqual(1);
|
||||
|
||||
expect(directResult.resources[0]).toMatchObject({
|
||||
id: creationResult[1].entity.id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
user_member: {
|
||||
user_id: platform.currentUser.id,
|
||||
},
|
||||
});
|
||||
|
||||
expect(directResult.resources[0].members).toContain(members[0]);
|
||||
expect(directResult.resources[0].members).toContain(members[1]);
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(1);
|
||||
expect(result.resources[0]).toMatchObject({
|
||||
id: creationResult[0].entity.id,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not return direct channels in workspace list", async done => {
|
||||
const channel = channelUtils.getChannel();
|
||||
const directChannelIn = channelUtils.getDirectChannel();
|
||||
const directChannelIn2 = channelUtils.getDirectChannel();
|
||||
const directChannelNotIn = channelUtils.getDirectChannel();
|
||||
const members = [platform.currentUser.id, uuidv1()];
|
||||
const directWorkspace: Workspace = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
};
|
||||
|
||||
const creationResult = await Promise.all([
|
||||
//This channel will automatically contains the requester because it is added automatically in it
|
||||
gr.services.channels.channels.save(channel, {}, getContext()),
|
||||
|
||||
//It will contain the currentUser
|
||||
gr.services.channels.channels.save(
|
||||
directChannelIn,
|
||||
{
|
||||
members,
|
||||
},
|
||||
{ ...getContext({ id: uuidv1() }), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
|
||||
//This channel will automatically contains the requester because it is added automatically in it
|
||||
gr.services.channels.channels.save(
|
||||
directChannelIn2,
|
||||
{
|
||||
members: [uuidv1(), uuidv1()],
|
||||
},
|
||||
{ ...getContext(), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
|
||||
//This channel will not contain the currentUser
|
||||
gr.services.channels.channels.save(
|
||||
directChannelNotIn,
|
||||
{
|
||||
members: [uuidv1(), uuidv1()],
|
||||
},
|
||||
{ ...getContext({ id: uuidv1() }), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
]);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(1);
|
||||
expect(result.resources[0]).toMatchObject({
|
||||
id: creationResult[0].entity.id,
|
||||
});
|
||||
expect(result.resources[0].visibility).not.toEqual(ChannelVisibility.DIRECT);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not return direct channels in workspace list with mine parameter", async done => {
|
||||
const channel = channelUtils.getChannel();
|
||||
const channel2 = channelUtils.getChannel();
|
||||
const directChannelIn = channelUtils.getDirectChannel();
|
||||
const directChannelNotIn = channelUtils.getDirectChannel();
|
||||
const members = [platform.currentUser.id, uuidv1()];
|
||||
const directWorkspace: Workspace = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
//This channel will automatically contains the requester because it is added automatically in it
|
||||
gr.services.channels.channels.save(channel, {}, getContext()),
|
||||
|
||||
//This channel will not contain currentUser
|
||||
gr.services.channels.channels.save(channel2, {}, getContext({ id: uuidv1() })),
|
||||
|
||||
//This channel will automatically contains the requester because it is added automatically in it
|
||||
gr.services.channels.channels.save(
|
||||
directChannelIn,
|
||||
{
|
||||
members,
|
||||
},
|
||||
{ ...getContext(), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
|
||||
gr.services.channels.channels.save(
|
||||
directChannelNotIn,
|
||||
{
|
||||
members: [uuidv1(), uuidv1(), uuidv1()],
|
||||
},
|
||||
{ ...getContext(), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
]);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
mine: "true",
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<Channel> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Create direct channel - POST /channels", () => {
|
||||
it("should be able to create a direct channel with members", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
|
||||
const members = [uuidv1(), platform.currentUser.id];
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
options: {
|
||||
members,
|
||||
},
|
||||
resource: {
|
||||
description: "A direct channel description",
|
||||
visibility: "direct",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(201);
|
||||
|
||||
const channelCreateResult: ResourceCreateResponse<Channel> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(channelCreateResult.resource).toBeDefined();
|
||||
|
||||
const createdChannel = await gr.services.channels.channels.get({
|
||||
id: channelCreateResult.resource.id,
|
||||
company_id: channelCreateResult.resource.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
});
|
||||
expect(createdChannel).toBeDefined();
|
||||
|
||||
const directChannelEntity = await gr.services.channels.channels.getDirectChannel({
|
||||
channel_id: createdChannel.id,
|
||||
company_id: createdChannel.company_id,
|
||||
users: DirectChannel.getUsersAsString(members),
|
||||
});
|
||||
expect(directChannelEntity).toBeDefined();
|
||||
|
||||
const directChannelsInCompany = await gr.services.channels.channels.getDirectChannelInCompany(
|
||||
createdChannel.company_id,
|
||||
members,
|
||||
);
|
||||
expect(directChannelsInCompany).toBeDefined();
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not be able to create the same direct channel twice (with same users)", async done => {
|
||||
function createChannel(members: string[]) {
|
||||
return platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
options: {
|
||||
members,
|
||||
},
|
||||
resource: {
|
||||
name: "Hello",
|
||||
visibility: "direct",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const members = [uuidv1(), platform.currentUser.id];
|
||||
const ids = new Set<string>();
|
||||
|
||||
let response = await createChannel(members);
|
||||
expect(response.statusCode).toEqual(201);
|
||||
let channelCreateResult: ResourceCreateResponse<Channel> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
response.body,
|
||||
);
|
||||
ids.add(channelCreateResult.resource.id);
|
||||
|
||||
response = await createChannel(members);
|
||||
expect(response.statusCode).toEqual(201);
|
||||
channelCreateResult = deserialize(ResourceCreateResponse, response.body);
|
||||
ids.add(channelCreateResult.resource.id);
|
||||
|
||||
expect(ids.size).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not be able to create the same direct channel twice (with same users not in the same order)", async done => {
|
||||
function createChannel(members: string[]) {
|
||||
return platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
options: {
|
||||
members,
|
||||
},
|
||||
resource: {
|
||||
name: "Hello",
|
||||
visibility: "direct",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const members = [uuidv1(), platform.currentUser.id];
|
||||
const ids = new Set<string>();
|
||||
|
||||
let response = await createChannel(members);
|
||||
expect(response.statusCode).toEqual(201);
|
||||
let channelCreateResult: ResourceCreateResponse<Channel> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
response.body,
|
||||
);
|
||||
ids.add(channelCreateResult.resource.id);
|
||||
|
||||
response = await createChannel(members.reverse());
|
||||
expect(response.statusCode).toEqual(201);
|
||||
channelCreateResult = deserialize(ResourceCreateResponse, response.body);
|
||||
ids.add(channelCreateResult.resource.id);
|
||||
|
||||
expect(ids.size).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import io from "socket.io-client";
|
||||
import { Channel, ChannelMember } from "../../../src/services/channels/entities";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ChannelUtils, get as getChannelUtils } from "./utils";
|
||||
import { getPublicRoomName } from "../../../src/services/channels/services/member/realtime";
|
||||
import { SaveResult } from "../../../src/core/platform/framework/api/crud-service";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe.skip("The Channels Members Realtime feature", () => {
|
||||
const url = "/internal/services/channels/v1";
|
||||
let platform: TestPlatform;
|
||||
let socket: SocketIOClient.Socket;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"channels",
|
||||
"auth",
|
||||
"database",
|
||||
"search",
|
||||
"realtime",
|
||||
],
|
||||
});
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
socket && socket.close();
|
||||
socket = null;
|
||||
});
|
||||
|
||||
function connect() {
|
||||
socket = io.connect("http://localhost:3000", { path: "/socket.io" });
|
||||
socket.connect();
|
||||
}
|
||||
|
||||
describe("On channel member creation", () => {
|
||||
let channel;
|
||||
let createdChannel: SaveResult<Channel>;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = channelUtils.getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext({ id: channel.owner }),
|
||||
);
|
||||
});
|
||||
|
||||
it("should notify the client", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", {
|
||||
name: getPublicRoomName(createdChannel.entity),
|
||||
token: roomToken,
|
||||
});
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: platform.currentUser.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(201);
|
||||
});
|
||||
socket.on("realtime:resource", event => {
|
||||
expect(event.type).toEqual("channel_member");
|
||||
expect(event.action).toEqual("saved");
|
||||
expect(event.resource).toMatchObject({
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
user_id: platform.currentUser.id,
|
||||
channel_id: createdChannel.entity.id,
|
||||
});
|
||||
done();
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("On channel member removal", () => {
|
||||
it("should notify the client", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
|
||||
const channel = channelUtils.getChannel(platform.currentUser.id);
|
||||
|
||||
const creationResult = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext({ id: channel.owner }),
|
||||
);
|
||||
const member = {
|
||||
channel_id: creationResult.entity.id,
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
} as ChannelMember;
|
||||
|
||||
await gr.services.channels.members.save(member, {
|
||||
channel: creationResult.entity,
|
||||
user: platform.currentUser,
|
||||
});
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.on("realtime:resource", event => {
|
||||
if (event.action !== "deleted") {
|
||||
// we can receive event when resource is created...
|
||||
return;
|
||||
}
|
||||
|
||||
expect(event.type).toEqual("channel_member");
|
||||
expect(event.action).toEqual("deleted");
|
||||
expect(event.resource).toMatchObject({
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
user_id: platform.currentUser.id,
|
||||
channel_id: creationResult.entity.id,
|
||||
});
|
||||
done();
|
||||
});
|
||||
socket.emit("realtime:join", {
|
||||
name: getPublicRoomName(creationResult.entity),
|
||||
token: roomToken,
|
||||
});
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${creationResult.entity.company_id}/workspaces/${creationResult.entity.workspace_id}/channels/${creationResult.entity.id}/members/${platform.currentUser.id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,401 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { v1 as uuidv1, v4 as uuidv4 } from "uuid";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { Channel } from "../../../src/services/channels/entities/channel";
|
||||
import { ChannelMember } from "../../../src/services/channels/entities/channel-member";
|
||||
import {
|
||||
ChannelExecutionContext,
|
||||
ChannelVisibility,
|
||||
WorkspaceExecutionContext,
|
||||
} from "../../../src/services/channels/types";
|
||||
import { ResourceGetResponse, ResourceListResponse, User } from "../../../src/utils/types";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe.skip("The ChannelMembers REST API", () => {
|
||||
const url = "/internal/services/channels/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: ["websocket", "webserver", "channels", "auth", "database"],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
});
|
||||
|
||||
function getWorkspaceContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
function getContext(channel: Channel, user?: User): ChannelExecutionContext {
|
||||
return {
|
||||
channel,
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new channel instance
|
||||
*
|
||||
* @param owner will be a random uuidv4 if not defined
|
||||
*/
|
||||
function getChannel(owner: string = uuidv1()): Channel {
|
||||
const channel = new Channel();
|
||||
|
||||
channel.name = "Test Channel";
|
||||
channel.company_id = platform.workspace.company_id;
|
||||
channel.workspace_id = platform.workspace.workspace_id;
|
||||
channel.is_default = false;
|
||||
channel.visibility = ChannelVisibility.PRIVATE;
|
||||
channel.archived = false;
|
||||
channel.owner = owner;
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
function getMember(channel: Channel, user: User): ChannelMember {
|
||||
const member = new ChannelMember();
|
||||
|
||||
member.company_id = platform.workspace.company_id;
|
||||
member.workspace_id = platform.workspace.workspace_id;
|
||||
member.channel_id = channel?.id;
|
||||
member.user_id = user?.id;
|
||||
|
||||
return member;
|
||||
}
|
||||
|
||||
describe("The GET / - Get members list", () => {
|
||||
let channel;
|
||||
let createdChannel;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(channel, {}, getWorkspaceContext());
|
||||
});
|
||||
|
||||
it("should 404 when channel does not exists", done => {
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return empty list of members", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<ChannelMember> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(0);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return list of members the user has access to", async done => {
|
||||
const member = getMember(createdChannel.entity, platform.currentUser);
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
getContext(channel),
|
||||
);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<ChannelMember> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toEqual(1);
|
||||
expect(result.resources[0]).toMatchObject({
|
||||
channel_id: memberCreationResult.entity.channel_id,
|
||||
workspace_id: memberCreationResult.entity.workspace_id,
|
||||
company_id: memberCreationResult.entity.company_id,
|
||||
user_id: memberCreationResult.entity.user_id,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The POST / - Add member", () => {
|
||||
let channel;
|
||||
let createdChannel;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(channel, {}, getWorkspaceContext());
|
||||
});
|
||||
|
||||
it("should fail when user_id is not defined", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(400);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should be able to add current member", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: platform.currentUser.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(201);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should be able to add another member", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: uuidv1(),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(201);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /:member_id - Get a member", () => {
|
||||
let channel;
|
||||
let createdChannel;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(channel, {}, getWorkspaceContext());
|
||||
});
|
||||
|
||||
it("should 404 when member does not exist", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${
|
||||
platform.workspace.workspace_id
|
||||
}/channels/${createdChannel.entity.id}/members/${uuidv1()}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should send back member", async done => {
|
||||
const member = getMember(createdChannel.entity, platform.currentUser);
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
getContext(channel),
|
||||
);
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members/${memberCreationResult.entity.user_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
const result: ResourceGetResponse<ChannelMember> = deserialize(
|
||||
ResourceGetResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource).toMatchObject({
|
||||
channel_id: memberCreationResult.entity.channel_id,
|
||||
workspace_id: memberCreationResult.entity.workspace_id,
|
||||
company_id: memberCreationResult.entity.company_id,
|
||||
user_id: memberCreationResult.entity.user_id,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The POST /:member_id - Update a member", () => {
|
||||
let channel;
|
||||
let createdChannel;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(channel, {}, getWorkspaceContext());
|
||||
});
|
||||
|
||||
it("should not be able to update a member when current user is not the member", async done => {
|
||||
const member = getMember(createdChannel.entity, { id: uuidv4() });
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
getContext(channel),
|
||||
);
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members/${memberCreationResult.entity.user_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
favorite: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(400);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should be able to update member when current user is the member", async done => {
|
||||
const member = getMember(createdChannel.entity, platform.currentUser);
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
getContext(channel),
|
||||
);
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members/${memberCreationResult.entity.user_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
favorite: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
|
||||
const channelMember: ChannelMember = await gr.services.channels.members.get(member);
|
||||
|
||||
expect(channelMember).toMatchObject({
|
||||
channel_id: memberCreationResult.entity.channel_id,
|
||||
workspace_id: memberCreationResult.entity.workspace_id,
|
||||
company_id: memberCreationResult.entity.company_id,
|
||||
user_id: memberCreationResult.entity.user_id,
|
||||
favorite: true,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The DELETE /:member_id - Remove a member", () => {
|
||||
let channel;
|
||||
let createdChannel;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel = getChannel();
|
||||
createdChannel = await gr.services.channels.channels.save(channel, {}, getWorkspaceContext());
|
||||
});
|
||||
|
||||
it("should 404 when member does not exist", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${
|
||||
platform.workspace.workspace_id
|
||||
}/channels/${createdChannel.entity.id}/members/${uuidv1()}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
favorite: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not be able to remove the member when current user does not have enough rights", async done => {
|
||||
// const member = getMember(createdChannel.entity, { id: uuidv4() });
|
||||
// const memberCreationResult = await gr.services.channels.members.save(member);
|
||||
// const jwtToken = await platform.auth.getJWTToken();
|
||||
// const response = await platform.app.inject({
|
||||
// method: "DELETE",
|
||||
// url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members/${memberCreationResult.entity.user_id}`,
|
||||
// headers: {
|
||||
// authorization: `Bearer ${jwtToken}`,
|
||||
// },
|
||||
// });
|
||||
//
|
||||
// expect(response.statusCode).toEqual(400);
|
||||
// done();
|
||||
});
|
||||
|
||||
it("should be able to remove the member when current user is the member", async done => {
|
||||
const member = getMember(createdChannel.entity, platform.currentUser);
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
getContext(channel),
|
||||
);
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/workspaces/${platform.workspace.workspace_id}/channels/${createdChannel.entity.id}/members/${memberCreationResult.entity.user_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(204);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { ChannelMember } from "../../../src/services/channels/entities";
|
||||
import { Channel } from "../../../src/services/channels/entities/channel";
|
||||
import {
|
||||
ChannelExecutionContext,
|
||||
ChannelVisibility,
|
||||
WorkspaceExecutionContext,
|
||||
} from "../../../src/services/channels/types";
|
||||
import { User } from "../../../src/utils/types";
|
||||
import { TestPlatform } from "../setup";
|
||||
|
||||
export interface ChannelUtils {
|
||||
getContext(user?: User): WorkspaceExecutionContext;
|
||||
getChannel(owner?: string): Channel;
|
||||
getDirectChannel(owner?: string): Channel;
|
||||
getChannelContext(channel: Channel, user: User): ChannelExecutionContext;
|
||||
}
|
||||
|
||||
export interface ChannelMemberUtils {
|
||||
getMember(channel: Channel, user: User): ChannelMember;
|
||||
}
|
||||
|
||||
export function getMemberUtils(platform: TestPlatform): ChannelMemberUtils {
|
||||
return {
|
||||
getMember,
|
||||
};
|
||||
|
||||
function getMember(channel: Channel, user: User): ChannelMember {
|
||||
const member = new ChannelMember();
|
||||
|
||||
member.company_id = platform.workspace.company_id;
|
||||
member.workspace_id = platform.workspace.workspace_id;
|
||||
member.channel_id = channel?.id;
|
||||
member.user_id = user?.id;
|
||||
|
||||
return member;
|
||||
}
|
||||
}
|
||||
|
||||
export function get(platform: TestPlatform): ChannelUtils {
|
||||
return {
|
||||
getContext,
|
||||
getChannel,
|
||||
getDirectChannel,
|
||||
getChannelContext,
|
||||
};
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
function getChannelContext(channel: Channel, user?: User): ChannelExecutionContext {
|
||||
return {
|
||||
channel,
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new channel instance
|
||||
*
|
||||
* @param owner will be a random uuidv4 if not defined
|
||||
*/
|
||||
function getChannel(owner: string = uuidv1()): Channel {
|
||||
const channel = new Channel();
|
||||
|
||||
channel.name = "Test Channel";
|
||||
channel.company_id = platform.workspace.company_id;
|
||||
channel.workspace_id = platform.workspace.workspace_id;
|
||||
channel.is_default = false;
|
||||
channel.visibility = ChannelVisibility.PUBLIC;
|
||||
channel.archived = false;
|
||||
channel.owner = owner;
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
function getDirectChannel(owner: string = uuidv1()): Channel {
|
||||
const channel = getChannel(owner);
|
||||
|
||||
channel.visibility = ChannelVisibility.DIRECT;
|
||||
channel.workspace_id = ChannelVisibility.DIRECT;
|
||||
channel.name = "A direct channel";
|
||||
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { afterAll, beforeAll, describe, expect, it as _it, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
export const itRemote = (name: string, cb: (a: any) => void) => {
|
||||
_it(name, async done => {
|
||||
if (gr.services.console.consoleType === "remote") {
|
||||
cb(done);
|
||||
} else {
|
||||
console.warn(`[skipped]: ${name} (console-mode only)`);
|
||||
done();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
describe("The console API auth", () => {
|
||||
const loginUrl = "/internal/services/console/v1/login";
|
||||
const tokenRefreshUrl = "/internal/services/console/v1/token";
|
||||
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
const companyId = uuidv1();
|
||||
|
||||
const firstEmail = "superman@email.com";
|
||||
|
||||
const firstUserPassword = "superPassw0rd";
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"message-queue",
|
||||
"search",
|
||||
"applications",
|
||||
"webserver",
|
||||
"user",
|
||||
"workspaces",
|
||||
"auth",
|
||||
"console",
|
||||
"storage",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
await platform.database.getConnector().init();
|
||||
testDbService = await TestDbService.getInstance(platform);
|
||||
await testDbService.createCompany(companyId);
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
// const ws1pk = { id: uuidv1(), company_id: companyId };
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
// await testDbService.createWorkspace(ws1pk);
|
||||
await testDbService.createUser([ws0pk], {
|
||||
companyRole: "member",
|
||||
workspaceRole: "moderator",
|
||||
email: firstEmail,
|
||||
firstName: "superman",
|
||||
password: firstUserPassword,
|
||||
});
|
||||
// await testDbService.createUser([ws0pk], "member", "member");
|
||||
// await testDbService.createUser([ws1pk], "member", "member", emailForExistedUser);
|
||||
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
await platform.tearDown();
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("Common checks", () => {
|
||||
it("should 400 when required params are missing ", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: "",
|
||||
password: "",
|
||||
remote_access_token: "",
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toMatchObject({
|
||||
statusCode: 400,
|
||||
error: "Bad Request",
|
||||
message: "remote_access_token or email+password are required",
|
||||
});
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Auth using token", () => {
|
||||
itRemote("should 403 when token is invalid", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
remote_access_token: "12345",
|
||||
},
|
||||
});
|
||||
expect(response.json()).toMatchObject({
|
||||
error: "Forbidden",
|
||||
message: "Bad access token credentials",
|
||||
statusCode: 403,
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
itRemote("should 200 when token is valid", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: "",
|
||||
password: "",
|
||||
remote_access_token: "a550c8b8b942bd92e447271343ac6b29",
|
||||
},
|
||||
});
|
||||
expect(response.json()).toMatchObject({
|
||||
access_token: {
|
||||
time: expect.any(Number),
|
||||
expiration: expect.any(Number),
|
||||
refresh_expiration: expect.any(Number),
|
||||
value: expect.any(String),
|
||||
refresh: expect.any(String),
|
||||
type: "Bearer",
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Auth using email/password", () => {
|
||||
it("should 403 when user doesn't exists", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: "randomEmail",
|
||||
password: "randomPass",
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json()).toMatchObject({
|
||||
error: "Forbidden",
|
||||
message: "User doesn't exists",
|
||||
statusCode: 403,
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when password doesn't match", async done => {
|
||||
const user = testDbService.users[0];
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: user.email_canonical,
|
||||
password: "randomPass",
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json()).toMatchObject({
|
||||
error: "Forbidden",
|
||||
message: "Password doesn't match",
|
||||
statusCode: 403,
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when credentials is valid", async done => {
|
||||
const user = testDbService.users[0];
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: user.email_canonical,
|
||||
password: firstUserPassword,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toMatchObject({
|
||||
access_token: {
|
||||
time: expect.any(Number),
|
||||
expiration: expect.any(Number),
|
||||
refresh_expiration: expect.any(Number),
|
||||
value: expect.any(String),
|
||||
refresh: expect.any(String),
|
||||
type: "Bearer",
|
||||
},
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Token renewal", () => {
|
||||
it("should 200 when refresh from access_token", async done => {
|
||||
const user = testDbService.users[0];
|
||||
|
||||
const firstResponse = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: user.email_canonical,
|
||||
password: firstUserPassword,
|
||||
},
|
||||
});
|
||||
|
||||
const firstRes = firstResponse.json().access_token;
|
||||
expect(firstRes.value).toBeTruthy();
|
||||
|
||||
setTimeout(async () => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${tokenRefreshUrl}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${firstRes.value}`,
|
||||
},
|
||||
});
|
||||
|
||||
const secondRes = response.json().access_token;
|
||||
|
||||
expect(secondRes.expiration).toBeGreaterThan(firstRes.expiration);
|
||||
expect(secondRes.refresh_expiration).toBeGreaterThan(firstRes.refresh_expiration);
|
||||
|
||||
done();
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
it("should 200 when refresh from refresh_token", async done => {
|
||||
const user = testDbService.users[0];
|
||||
|
||||
const firstResponse = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${loginUrl}`,
|
||||
payload: {
|
||||
email: user.email_canonical,
|
||||
password: firstUserPassword,
|
||||
},
|
||||
});
|
||||
|
||||
const firstRes = firstResponse.json().access_token;
|
||||
expect(firstRes.refresh).toBeTruthy();
|
||||
|
||||
setTimeout(async () => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${tokenRefreshUrl}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${firstRes.refresh}`,
|
||||
},
|
||||
});
|
||||
|
||||
const secondRes = response.json().access_token;
|
||||
|
||||
expect(secondRes.expiration).toBeGreaterThan(firstRes.expiration);
|
||||
expect(secondRes.refresh_expiration).toBeGreaterThan(firstRes.refresh_expiration);
|
||||
|
||||
done();
|
||||
}, 2000);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,545 @@
|
||||
import { afterAll, beforeAll, describe, expect, it as _it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { sign as cryptoSign } from "crypto";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
import { ConsoleServiceImpl } from "../../../src/services/console/service";
|
||||
/*
|
||||
THIS TESTS RUNS ONLY FOR THE CONSOLE-MODE (CONSOLE TYPE: REMOTE)
|
||||
*/
|
||||
|
||||
export const it = (name: string, cb: (a: any) => void) => {
|
||||
_it(name, async done => {
|
||||
if (gr.services.console.consoleType === "remote") {
|
||||
cb(done);
|
||||
} else {
|
||||
console.warn(`[skipped]: ${name} (console-mode only)`);
|
||||
done();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
describe("The console API hooks", () => {
|
||||
const url = "/internal/services/console/v1/hook";
|
||||
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
const companyId = uuidv1();
|
||||
|
||||
const firstEmail = "superman@email.com";
|
||||
const secondEmail = "C.o.n.sole_created-user@email.com";
|
||||
const thirdEmail = "superman@someogherservice.com";
|
||||
|
||||
const secret = "ohquoo1fohzeigitochaJeepoowug4Yuqueite6etojieg1oowaeraeshiW8ku8g";
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"message-queue",
|
||||
"webserver",
|
||||
"search",
|
||||
"user",
|
||||
"workspaces",
|
||||
"auth",
|
||||
"console",
|
||||
"applications",
|
||||
"storage",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
await platform.database.getConnector().init();
|
||||
testDbService = await TestDbService.getInstance(platform);
|
||||
await testDbService.createCompany(companyId);
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
|
||||
await testDbService.createUser([ws0pk], {
|
||||
companyRole: "member",
|
||||
workspaceRole: "moderator",
|
||||
username: "superman",
|
||||
});
|
||||
|
||||
const console = platform.platform.getProvider<ConsoleServiceImpl>("console");
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
await platform.tearDown();
|
||||
ends();
|
||||
});
|
||||
|
||||
const getPayload = (type: string, content: Record<any, any>) => {
|
||||
const data = {
|
||||
content: content,
|
||||
type: type,
|
||||
} as any;
|
||||
|
||||
const sign = cryptoSign(
|
||||
"RSA-SHA512",
|
||||
Buffer.from(JSON.stringify(data)),
|
||||
"-----BEGIN PRIVATE KEY-----\nMIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQD15kALIEHoe1bt\nADG/oOqHLRgnzNoiGl8aQ6LD/9c4F5+IVP9gPxGm26haSMW2Z9doJeTucvV8syQV\nbdwc9z0NUhNhFG1RLsj0+ePgpuBfKv+uzEICrRedP7wsmWC37K1NmGZ+LzO21oeu\nLO0L39kNk+qspJnqqx8PIfUmeQ6DDkEKW/J0ISeOsBOetKiJC2n5F4Fkifh1Bq2T\nsFfW9Tz47hfLAKkNUyoulBbqX/xViUhlhFb59sxhoMesCL/VJf7OmTLvryXBW/TU\nCYFssAZXXSWOOzc2k+X2VX3QslKfCHsnCO75I+FPFd9YtFWKlaHeq36ZHlYxnYqp\nRcdixzhjAgMBAAECggEANtvoe9L1gUVLDlLVxnfC+udflTmJjMQvZW+jd3Czdisn\nB0ZXNwS7DmvA8mt72IbwMqcJnPz+sZRRv4oj6j5qW3dtJWJmRQ9X+/doFG2GbxTr\nt/aP34L4WremZpjNUBs4SrBuZUZolijkWkJhnB2Tkgjm+R87y3Pj2P9tbujhCPGM\nMQf+s5lOh/AXDyqYGyEJAZBJT3DevrB9Cl3uhYWZ0fFUz4hwATeB0Va8YT8ZJea2\nXwajg/NnOOpdSGVgv0+7zhPYvkvg8bMZeH24VxYkAfdww8vANPuk4wUwDvnh39+Q\nI4uHQGXgjf8SJ5Z7G7A5Q4r7Ma4drJDbCOfNTi84+QKBgQD+ar48b7c5ffMT/ta7\nGUfMiHCjLfauHt/1f1CkFN1OpJW2ZrS34jYusqBXos32X2gx+wsOGtzOrhkkpvgp\nL7jaZmUnQTwfn6Sx4Duq+LVVMH/uj+W/Zj24AKnoylzM9XC6D2kwKAfHs4Mg6+fe\no6VRBR/yw01ShR+YDVAEN0B7ZwKBgQD3bfCIlp1DpTjFKEBFaC4jRNJPaf8OLt/U\nYHOBwwltb406I4s13M3A1N74Btk5ycx6n/a6RHIGB6+E2xn9AnYI51M/+n9vBLPc\nnnqjOZP/7FdK7qL/g4JtXae/CyroXYaYXUNsdJttQC62QRW+xhp6fYxWt/nAcc9R\nvXmninx5pQJ/CPG3vmgvCNZktU9APVOmMoqZayMyiOyM8xSGwT36ick/eioiMFTD\nkuC0wl/23bJ890TcHqLTIHD+cUttbgU/em4fIEIq2vHB2H8JmfkkZtpNpRVp/lCZ\n2t4rGwQCPzJhxCjGiereWyb0dTPV8v3N0gtcFCzJix0i/zV4mq1WlwKBgGfV1F6N\nznun57YdmTNHcC1O4W+ATRA3rakjvPWU0u0BJmRirDYzbolhDB1MSncM7+n6HYG3\n3Z4YNZlslXBvSveblH1B8560e4K3Y0IClNCO72c71F2kY+Tfq9jpp90R+r0QTo5C\nNUPY7oF/uM9xtYT4ESAHXyFa4aUs/dPIs0odAoGBAKYqeAsbLIsb2ruMkeH5itbe\nxdgVHZ8d2Pxk1h+52SGyptuBzlt7c6Gb3KNxpIc61tZklOn5yj+QmJHN82rXGdIE\nCkdrkEmqZU52X2OInozV1Py8L7akH9wijzy5ULWqxapIE2ItnPkgcC7+x6vglkfd\nI0VcGHm8cgqCpzRaIZjH\n-----END PRIVATE KEY-----",
|
||||
);
|
||||
|
||||
data.signature = sign.toString("base64");
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
describe("Common checks", () => {
|
||||
it("should 404 when not POST ", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 400 when secret key is missing", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}`,
|
||||
payload: getPayload("a", {}),
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toMatchObject({
|
||||
statusCode: 400,
|
||||
error: "Bad Request",
|
||||
message: "querystring should have required property 'secret_key'",
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when secret key is not valid ", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=wrongOne`,
|
||||
payload: getPayload("a", {}),
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json()).toMatchObject({
|
||||
statusCode: 403,
|
||||
error: "Forbidden",
|
||||
message: "Wrong secret",
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 501 when type is not implemented", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("unknown_type", {}),
|
||||
});
|
||||
expect(response.statusCode).toBe(501);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("User related hooks", () => {
|
||||
describe("User created/updated", () => {
|
||||
it("should 200 when updated existing user", async done => {
|
||||
const user = testDbService.users[0];
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("user_updated", {
|
||||
user: {
|
||||
_id: user.identity_provider_id,
|
||||
roles: [
|
||||
{ targetCode: companyId, roleCode: "owner", applications: [{ code: "twake" }] },
|
||||
],
|
||||
email: firstEmail,
|
||||
firstName: "firstName",
|
||||
lastName: "lastName",
|
||||
isVerified: true,
|
||||
preference: {
|
||||
locale: "en",
|
||||
timeZone: 2,
|
||||
},
|
||||
avatar: {
|
||||
type: "unknown",
|
||||
value: "123456.jpg",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const updatedUser = await testDbService.getUserFromDb({
|
||||
id: user.id,
|
||||
});
|
||||
|
||||
expect(updatedUser).toMatchObject({
|
||||
id: user.id,
|
||||
email_canonical: firstEmail,
|
||||
first_name: "firstName",
|
||||
last_name: "lastName",
|
||||
mail_verified: true,
|
||||
timezone: 2,
|
||||
language: "en",
|
||||
picture:
|
||||
gr.services.console.consoleOptions.url.replace(/\/$/, "") + "/avatars/123456.jpg",
|
||||
});
|
||||
|
||||
const userRoles = await testDbService.getCompanyUser(companyId, updatedUser.id);
|
||||
|
||||
expect(userRoles).toEqual(
|
||||
expect.objectContaining({
|
||||
role: "owner",
|
||||
}),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when creating new user", async done => {
|
||||
const newUserConsoleId = String(testDbService.rand());
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("user_updated", {
|
||||
user: {
|
||||
_id: newUserConsoleId,
|
||||
roles: [
|
||||
{ targetCode: companyId, roleCode: "admin", applications: [{ code: "twake" }] },
|
||||
],
|
||||
email: secondEmail,
|
||||
firstName: "consoleFirst",
|
||||
lastName: "consoleSecond",
|
||||
isVerified: true,
|
||||
preference: {
|
||||
locale: "ru",
|
||||
timeZone: 3,
|
||||
},
|
||||
avatar: {
|
||||
type: "unknown",
|
||||
value: "5678.jpg",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const updatedUser = await testDbService.getUserFromDb({
|
||||
identity_provider_id: newUserConsoleId,
|
||||
});
|
||||
|
||||
expect(updatedUser).toMatchObject({
|
||||
first_name: "consoleFirst",
|
||||
last_name: "consoleSecond",
|
||||
mail_verified: true,
|
||||
timezone: 3,
|
||||
language: "ru",
|
||||
creation_date: expect.any(String),
|
||||
deleted: false,
|
||||
email_canonical: secondEmail.toLocaleLowerCase(),
|
||||
identity_provider: "console",
|
||||
identity_provider_id: newUserConsoleId,
|
||||
username_canonical: "consolecreateduser",
|
||||
picture: gr.services.console.consoleOptions.url.replace(/\/$/, "") + "/avatars/5678.jpg",
|
||||
});
|
||||
|
||||
const userRoles = await testDbService.getCompanyUser(companyId, updatedUser.id);
|
||||
|
||||
expect(userRoles).toEqual(
|
||||
expect.objectContaining({
|
||||
role: "moderator",
|
||||
}),
|
||||
);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when creating new user with same username (generating new one)", async done => {
|
||||
const newUserConsoleId = String(testDbService.rand());
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("user_updated", {
|
||||
user: {
|
||||
_id: newUserConsoleId,
|
||||
roles: [
|
||||
{ targetCode: companyId, roleCode: "member", applications: [{ code: "twake" }] },
|
||||
],
|
||||
email: thirdEmail,
|
||||
firstName: "superman",
|
||||
lastName: "superman-lastname",
|
||||
isVerified: true,
|
||||
preference: {
|
||||
locale: "ru",
|
||||
timeZone: 3,
|
||||
},
|
||||
avatar: {
|
||||
type: "unknown",
|
||||
value: "5679.jpg",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const updatedUser = await testDbService.getUserFromDb({
|
||||
identity_provider_id: newUserConsoleId,
|
||||
});
|
||||
|
||||
expect(updatedUser).toMatchObject({
|
||||
first_name: "superman",
|
||||
last_name: "superman-lastname",
|
||||
mail_verified: true,
|
||||
timezone: 3,
|
||||
language: "ru",
|
||||
creation_date: expect.any(String),
|
||||
deleted: false,
|
||||
email_canonical: thirdEmail.toLocaleLowerCase(),
|
||||
identity_provider: "console",
|
||||
identity_provider_id: newUserConsoleId,
|
||||
username_canonical: "superman1",
|
||||
picture: gr.services.console.consoleOptions.url.replace(/\/$/, "") + "/avatars/5679.jpg",
|
||||
});
|
||||
|
||||
const userRoles = await testDbService.getCompanyUser(companyId, updatedUser.id);
|
||||
|
||||
expect(userRoles).toEqual(
|
||||
expect.objectContaining({
|
||||
role: "member",
|
||||
}),
|
||||
);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 400 when creating user with email that already exists", async done => {
|
||||
const newUserConsoleId = String(testDbService.rand());
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("user_updated", {
|
||||
user: {
|
||||
_id: newUserConsoleId,
|
||||
email: firstEmail,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toMatchObject({
|
||||
error: "Console user not created because email already exists",
|
||||
});
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("User removed", () => {
|
||||
it("should 200 when deleting", async done => {
|
||||
const company = testDbService.company;
|
||||
let users = await testDbService.getCompanyUsers(company.id);
|
||||
let user = users.find(a => a.username_canonical == "consolecreateduser");
|
||||
expect(user).toBeTruthy();
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("company_user_deactivated", {
|
||||
company: { code: company.identity_provider_id },
|
||||
user: {
|
||||
_id: user.identity_provider_id,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
users = await testDbService.getCompanyUsers(company.id);
|
||||
user = users.find(a => a.username_canonical == "consolecreateduser");
|
||||
expect(user).toBeFalsy();
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 400 when user not found", async done => {
|
||||
const company = testDbService.company;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("company_user_deactivated", {
|
||||
company: { code: company.identity_provider_id },
|
||||
user: {
|
||||
_id: 123456789,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Company related hooks", () => {
|
||||
describe("Company added", () => {
|
||||
it("should 200 when company created", async done => {
|
||||
const newCompanyCode = String(testDbService.rand());
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("company_created", {
|
||||
company: {
|
||||
code: newCompanyCode,
|
||||
stats: "stats",
|
||||
plan: { name: "plan name", limits: {} },
|
||||
value: "value",
|
||||
details: {
|
||||
logo: "logo",
|
||||
avatar: {
|
||||
value: "avatar.jpg",
|
||||
type: "type",
|
||||
},
|
||||
name: "company name",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const createdCompany = await testDbService.getCompanyFromDbByCode(newCompanyCode);
|
||||
expect(createdCompany).toEqual(
|
||||
expect.objectContaining({
|
||||
id: expect.any(String),
|
||||
name: "company name",
|
||||
plan: { name: "plan name", limits: {} },
|
||||
stats: "stats",
|
||||
logo: "logo",
|
||||
dateAdded: expect.any(Number),
|
||||
identity_provider: "console",
|
||||
identity_provider_id: newCompanyCode,
|
||||
// details:
|
||||
}),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Company updated", () => {
|
||||
it("should 200 when company updated", async done => {
|
||||
const company = testDbService.company;
|
||||
expect(company).toBeTruthy();
|
||||
expect(company.identity_provider_id).toBeTruthy();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("company_updated", {
|
||||
company: {
|
||||
code: company.identity_provider_id,
|
||||
stats: "stats",
|
||||
plan: { name: "plan name", limits: {} },
|
||||
value: "value",
|
||||
details: {
|
||||
logo: "logo",
|
||||
avatar: {
|
||||
value: "avatar.jpg",
|
||||
type: "type",
|
||||
},
|
||||
name: "new company name",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const createdCompany = await testDbService.getCompanyFromDb(company.id);
|
||||
expect(createdCompany).toEqual(
|
||||
expect.objectContaining({
|
||||
id: company.id,
|
||||
name: "new company name",
|
||||
plan: { name: "plan name", limits: {} },
|
||||
stats: "stats",
|
||||
logo: "logo",
|
||||
dateAdded: expect.any(Number),
|
||||
identity_provider: "console",
|
||||
identity_provider_id: company.identity_provider_id,
|
||||
// details:
|
||||
}),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("Plan updated", () => {
|
||||
it("should 200 when plan updated", async done => {
|
||||
const company = testDbService.company;
|
||||
expect(company).toBeTruthy();
|
||||
expect(company.identity_provider_id).toBeTruthy();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("plan_updated", {
|
||||
company: {
|
||||
code: company.identity_provider_id,
|
||||
plan: { name: "another plan name", limits: {} },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const createdCompany = await testDbService.getCompanyFromDb(company.id);
|
||||
expect(createdCompany).toEqual(
|
||||
expect.objectContaining({
|
||||
id: company.id,
|
||||
name: "new company name",
|
||||
plan: { name: "another plan name", limits: {} },
|
||||
stats: "stats",
|
||||
logo: "logo",
|
||||
dateAdded: expect.any(Number),
|
||||
identity_provider: "console",
|
||||
identity_provider_id: company.identity_provider_id,
|
||||
// details:
|
||||
}),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Company removed", () => {
|
||||
it("should 200 when company removed", async done => {
|
||||
const company = testDbService.company;
|
||||
expect(company).toBeTruthy();
|
||||
expect(company.identity_provider_id).toBeTruthy();
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}?secret_key=${secret}`,
|
||||
payload: getPayload("company_deleted", {
|
||||
company: {
|
||||
code: company.identity_provider_id,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const deletedCompany = await testDbService.getCompanyFromDb(company.id);
|
||||
expect(deletedCompany).toBeFalsy();
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-nocheck
|
||||
import { beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "./setup";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { CounterAPI } from "../../src/core/platform/services/counter/types";
|
||||
import {
|
||||
WorkspaceCounterEntity,
|
||||
WorkspaceCounterPrimaryKey,
|
||||
WorkspaceCounterType,
|
||||
} from "../../src/services/workspaces/entities/workspace_counters";
|
||||
import { CounterProvider } from "../../src/core/platform/services/counter/provider";
|
||||
import WorkspaceUser, {
|
||||
getInstance as getWorkspaceUserInstance,
|
||||
TYPE as WorkspaceUserEntityType,
|
||||
} from "../../src/services/workspaces/entities/workspace_user";
|
||||
|
||||
import { countRepositoryItems } from "../../src/utils/counters";
|
||||
import { TestDbService } from "./utils.prepare.db";
|
||||
import {
|
||||
ChannelCounterEntity,
|
||||
ChannelCounterPrimaryKey,
|
||||
ChannelUserCounterType,
|
||||
} from "../../src/services/channels/entities/channel-counters";
|
||||
import { ChannelMemberType } from "../../src/services/channels/types";
|
||||
import { getMemberOfChannelInstance, MemberOfChannel } from "../../src/services/channels/entities";
|
||||
import gr from "../../src/services/global-resolver";
|
||||
|
||||
describe("Counters implementation", () => {
|
||||
let platform: TestPlatform;
|
||||
// let database: DatabaseServiceAPI;
|
||||
let counterApi: CounterAPI;
|
||||
let testDbService: TestDbService;
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init();
|
||||
|
||||
testDbService = new TestDbService(platform);
|
||||
|
||||
await gr.database.getConnector().drop();
|
||||
|
||||
counterApi = platform.platform.getProvider<CounterAPI>("counter");
|
||||
expect(counterApi).toBeTruthy();
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(done => {
|
||||
platform.tearDown().then(done);
|
||||
});
|
||||
|
||||
const getCounter = async (type, entity) => {
|
||||
return counterApi.getCounter<entity>(await testDbService.getRepository<entity>(type, entity));
|
||||
};
|
||||
|
||||
describe("Workspace counters", () => {
|
||||
let counter: CounterProvider;
|
||||
const counterPk = { id: uuidv1(), counter_type: WorkspaceCounterType.MEMBERS };
|
||||
|
||||
beforeAll(async ends => {
|
||||
counter = await getCounter("workspace_counters", WorkspaceCounterEntity);
|
||||
|
||||
const workspaceUserRepository = await testDbService.getRepository(
|
||||
WorkspaceUserEntityType,
|
||||
WorkspaceUser,
|
||||
);
|
||||
|
||||
await workspaceUserRepository.save(
|
||||
getWorkspaceUserInstance({
|
||||
workspaceId: counterPk.id,
|
||||
userId: uuidv1(),
|
||||
id: uuidv1(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(counter).toBeTruthy();
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
it("Initializing empty value", async done => {
|
||||
await counter.increase(counterPk, 0);
|
||||
const val = await counter.get(counterPk);
|
||||
expect(val).toEqual(0);
|
||||
done();
|
||||
});
|
||||
|
||||
it("Adding value", async done => {
|
||||
// adding 1
|
||||
|
||||
await counter.increase(counterPk, 1);
|
||||
let val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
// adding 2
|
||||
|
||||
await counter.increase(counterPk, 2);
|
||||
val = await counter.get(counterPk);
|
||||
expect(val).toEqual(3);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("Subtracting value", async done => {
|
||||
// Subtracting 2
|
||||
|
||||
await counter.increase(counterPk, -2);
|
||||
let val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
// Subtracting 10
|
||||
|
||||
await counter.increase(counterPk, -10);
|
||||
val = await counter.get(counterPk);
|
||||
expect(val).toEqual(-9);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("Revising counter", async done => {
|
||||
// Subtracting 2
|
||||
|
||||
const workspaceUserRepository = await testDbService.getRepository(
|
||||
WorkspaceUserEntityType,
|
||||
WorkspaceUser,
|
||||
);
|
||||
|
||||
counter.setReviseCallback(async (pk: WorkspaceCounterPrimaryKey) => {
|
||||
if (pk.counter_type == "members") {
|
||||
return countRepositoryItems(workspaceUserRepository, { workspace_id: pk.id });
|
||||
}
|
||||
}, 4);
|
||||
|
||||
await counter.increase(counterPk, 1);
|
||||
const val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Channel counters", () => {
|
||||
let counter: CounterProvider;
|
||||
let counterPk: ChannelCounterPrimaryKey;
|
||||
|
||||
beforeAll(async ends => {
|
||||
counterPk = {
|
||||
id: uuidv1(),
|
||||
company_id: uuidv1(),
|
||||
workspace_id: uuidv1(),
|
||||
counter_type: ChannelUserCounterType.MEMBERS,
|
||||
};
|
||||
|
||||
counter = await getCounter("channel_counters", ChannelCounterEntity);
|
||||
|
||||
const memberOfChannelRepository = await testDbService.getRepository(
|
||||
"channel_members",
|
||||
MemberOfChannel,
|
||||
);
|
||||
|
||||
await memberOfChannelRepository.save(
|
||||
getMemberOfChannelInstance({
|
||||
company_id: counterPk.company_id,
|
||||
workspace_id: counterPk.workspace_id,
|
||||
channel_id: counterPk.id,
|
||||
user_id: uuidv1(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(counter).toBeTruthy();
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
it("Initializing empty value", async done => {
|
||||
await counter.increase(counterPk, 0);
|
||||
const val = await counter.get(counterPk);
|
||||
expect(val).toEqual(0);
|
||||
done();
|
||||
});
|
||||
|
||||
it("Adding value", async done => {
|
||||
// adding 1
|
||||
|
||||
await counter.increase(counterPk, 1);
|
||||
let val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
// adding 2
|
||||
|
||||
await counter.increase(counterPk, 2);
|
||||
val = await counter.get(counterPk);
|
||||
expect(val).toEqual(3);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("Subtracting value", async done => {
|
||||
// Subtracting 2
|
||||
|
||||
await counter.increase(counterPk, -2);
|
||||
let val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
// Subtracting 10
|
||||
|
||||
await counter.increase(counterPk, -10);
|
||||
val = await counter.get(counterPk);
|
||||
expect(val).toEqual(-9);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("Revising counter", async done => {
|
||||
// Subtracting 2
|
||||
|
||||
const memberOfChannelRepository = await testDbService.getRepository(
|
||||
"channel_members",
|
||||
MemberOfChannel,
|
||||
);
|
||||
|
||||
counter.setReviseCallback(async (pk: ChannelCounterPrimaryKey) => {
|
||||
if (pk.counter_type == ChannelUserCounterType.MEMBERS) {
|
||||
return countRepositoryItems(
|
||||
memberOfChannelRepository,
|
||||
{ channel_id: pk.id, company_id: pk.company_id, workspace_id: pk.workspace_id },
|
||||
{ type: ChannelMemberType.MEMBER },
|
||||
);
|
||||
}
|
||||
}, 4);
|
||||
|
||||
await counter.increase(counterPk, 1);
|
||||
const val = await counter.get(counterPk);
|
||||
expect(val).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
test
|
||||
@@ -0,0 +1,183 @@
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { AccessInformation } from "../../../src/services/documents/entities/drive-file";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { e2e_createDocument, e2e_getDocument } from "./utils";
|
||||
|
||||
const url = "/internal/services/documents/v1";
|
||||
|
||||
describe("the Drive Twake tabs feature", () => {
|
||||
let platform: TestPlatform;
|
||||
|
||||
class DriveFileMockClass {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
added: string;
|
||||
parent_id: string;
|
||||
access_info: AccessInformation;
|
||||
}
|
||||
|
||||
class DriveItemDetailsMockClass {
|
||||
path: string[];
|
||||
item: DriveFileMockClass;
|
||||
children: DriveFileMockClass[];
|
||||
versions: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"applications",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"files",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
"documents",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await platform.app.close();
|
||||
});
|
||||
|
||||
it("did create a tab configuration on Drive side", async done => {
|
||||
await TestDbService.getInstance(platform, true);
|
||||
|
||||
const item = {
|
||||
name: "new tab test file",
|
||||
parent_id: "root",
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
|
||||
const version = {};
|
||||
|
||||
const response = await e2e_createDocument(platform, item, version);
|
||||
const doc = deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
|
||||
|
||||
const tab = {
|
||||
company_id: platform.workspace.company_id,
|
||||
tab_id: "1234567890",
|
||||
channel_id: "abcdefghij",
|
||||
item_id: doc.id,
|
||||
level: "write",
|
||||
};
|
||||
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
const createdTab = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload: tab,
|
||||
});
|
||||
|
||||
expect(createdTab.statusCode).toBe(200);
|
||||
expect(createdTab.body).toBeDefined();
|
||||
expect(createdTab.json().company_id).toBe(tab.company_id);
|
||||
expect(createdTab.json().tab_id).toBe(tab.tab_id);
|
||||
expect(createdTab.json().item_id).toBe(tab.item_id);
|
||||
|
||||
const getTabResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(getTabResponse.statusCode).toBe(200);
|
||||
expect(getTabResponse.body).toBeDefined();
|
||||
expect(getTabResponse.json().company_id).toBe(tab.company_id);
|
||||
expect(getTabResponse.json().tab_id).toBe(tab.tab_id);
|
||||
expect(getTabResponse.json().item_id).toBe(tab.item_id);
|
||||
|
||||
const documentResponse = await e2e_getDocument(platform, doc.id);
|
||||
const documentResult = deserialize<DriveItemDetailsMockClass>(
|
||||
DriveItemDetailsMockClass,
|
||||
documentResponse.body,
|
||||
);
|
||||
|
||||
console.log(documentResult?.item);
|
||||
|
||||
expect(
|
||||
documentResult?.item?.access_info?.entities?.find(
|
||||
a => a?.type === "channel" && a.id === "abcdefghij" && a.level === "write",
|
||||
),
|
||||
).toBeDefined();
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did refuse to create a tab configuration for an item I can't manage", async done => {
|
||||
const dbService = await TestDbService.getInstance(platform, true);
|
||||
const ws0pk = {
|
||||
id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
const otherUser = await dbService.createUser([ws0pk]);
|
||||
|
||||
const item = {
|
||||
name: "new tab test file",
|
||||
parent_id: "root",
|
||||
company_id: platform.workspace.company_id,
|
||||
access_info: {
|
||||
entities: [
|
||||
{
|
||||
type: "folder",
|
||||
id: "parent",
|
||||
level: "none",
|
||||
} as any,
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const version = {};
|
||||
|
||||
const response = await e2e_createDocument(platform, item, version);
|
||||
const doc = deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
|
||||
|
||||
const tab = {
|
||||
company_id: platform.workspace.company_id,
|
||||
tab_id: "1234567890",
|
||||
channel_id: "abcdefghij",
|
||||
item_id: doc.id,
|
||||
level: "read",
|
||||
};
|
||||
|
||||
const token = await platform.auth.getJWTToken({ sub: otherUser.id });
|
||||
|
||||
const createdTab = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload: tab,
|
||||
});
|
||||
|
||||
expect(createdTab.statusCode).toBe(403);
|
||||
|
||||
done?.();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, beforeEach, afterEach, it, expect, afterAll } from "@jest/globals";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { File } from "../../../src/services/files/entities/file";
|
||||
import { ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import {
|
||||
e2e_createDocument,
|
||||
e2e_createDocumentFile,
|
||||
e2e_createVersion,
|
||||
e2e_deleteDocument,
|
||||
e2e_getDocument,
|
||||
e2e_searchDocument,
|
||||
e2e_updateDocument,
|
||||
} from "./utils";
|
||||
|
||||
describe("the Drive feature", () => {
|
||||
let platform: TestPlatform;
|
||||
|
||||
class DriveFileMockClass {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
added: string;
|
||||
parent_id: string;
|
||||
}
|
||||
|
||||
class DriveItemDetailsMockClass {
|
||||
path: string[];
|
||||
item: DriveFileMockClass;
|
||||
children: DriveFileMockClass[];
|
||||
versions: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
class SearchResultMockClass {
|
||||
entities: DriveFileMockClass[];
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"applications",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"files",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
"documents",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await platform.app.close();
|
||||
});
|
||||
|
||||
const createItem = async (): Promise<DriveFileMockClass> => {
|
||||
await TestDbService.getInstance(platform, true);
|
||||
|
||||
const item = {
|
||||
name: "new test file",
|
||||
parent_id: "root",
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
|
||||
const version = {};
|
||||
|
||||
const response = await e2e_createDocument(platform, item, version);
|
||||
return deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
|
||||
};
|
||||
|
||||
it("did create the drive item", async done => {
|
||||
const result = await createItem();
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.name).toEqual("new test file");
|
||||
expect(result.added).toBeDefined();
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did fetch the drive item", async done => {
|
||||
await TestDbService.getInstance(platform, true);
|
||||
|
||||
const response = await e2e_getDocument(platform, "");
|
||||
const result = deserialize<DriveItemDetailsMockClass>(DriveItemDetailsMockClass, response.body);
|
||||
|
||||
expect(result.item.name).toEqual("root");
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did fetch the trash", async done => {
|
||||
await TestDbService.getInstance(platform, true);
|
||||
|
||||
const response = await e2e_getDocument(platform, "trash");
|
||||
const result = deserialize<DriveItemDetailsMockClass>(DriveItemDetailsMockClass, response.body);
|
||||
|
||||
expect(result.item.name).toEqual("trash");
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did delete an item", async done => {
|
||||
const createItemResult = await createItem();
|
||||
|
||||
expect(createItemResult.id).toBeDefined();
|
||||
|
||||
const deleteResponse = await e2e_deleteDocument(platform, createItemResult.id);
|
||||
expect(deleteResponse.statusCode).toEqual(200);
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did update an item", async done => {
|
||||
const createItemResult = await createItem();
|
||||
|
||||
expect(createItemResult.id).toBeDefined();
|
||||
|
||||
const update = {
|
||||
name: "somethingelse",
|
||||
};
|
||||
|
||||
const updateItemResponse = await e2e_updateDocument(platform, createItemResult.id, update);
|
||||
const updateItemResult = deserialize<DriveFileMockClass>(
|
||||
DriveFileMockClass,
|
||||
updateItemResponse.body,
|
||||
);
|
||||
|
||||
expect(createItemResult.id).toEqual(updateItemResult.id);
|
||||
expect(updateItemResult.name).toEqual("somethingelse");
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did move an item to trash", async done => {
|
||||
const createItemResult = await createItem();
|
||||
|
||||
expect(createItemResult.id).toBeDefined();
|
||||
|
||||
const moveToTrashResponse = await e2e_deleteDocument(platform, createItemResult.id);
|
||||
expect(moveToTrashResponse.statusCode).toEqual(200);
|
||||
|
||||
const listTrashResponse = await e2e_getDocument(platform, "trash");
|
||||
const listTrashResult = deserialize<DriveItemDetailsMockClass>(
|
||||
DriveItemDetailsMockClass,
|
||||
listTrashResponse.body,
|
||||
);
|
||||
|
||||
expect(listTrashResult.item.name).toEqual("trash");
|
||||
expect(listTrashResult.children.some(({ id }) => id === createItemResult.id)).toBeTruthy();
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
// TODO: wait for elastic search index
|
||||
it("did search for an item", async done => {
|
||||
const createItemResult = await createItem();
|
||||
|
||||
expect(createItemResult.id).toBeDefined();
|
||||
|
||||
await e2e_getDocument(platform, "root");
|
||||
await e2e_getDocument(platform, createItemResult.id);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||
|
||||
const searchPayload = {
|
||||
search: "test",
|
||||
};
|
||||
|
||||
const searchResponse = await e2e_searchDocument(platform, searchPayload);
|
||||
const searchResult = deserialize<SearchResultMockClass>(
|
||||
SearchResultMockClass,
|
||||
searchResponse.body,
|
||||
);
|
||||
|
||||
expect(searchResult.entities.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did search for an item that doesn't exist", async done => {
|
||||
await createItem();
|
||||
|
||||
const unexistingSeachPayload = {
|
||||
search: "somethingthatdoesn'tandshouldn'texist",
|
||||
};
|
||||
const failSearchResponse = await e2e_searchDocument(platform, unexistingSeachPayload);
|
||||
const failSearchResult = deserialize<SearchResultMockClass>(
|
||||
SearchResultMockClass,
|
||||
failSearchResponse.body,
|
||||
);
|
||||
|
||||
expect(failSearchResult.entities).toHaveLength(0);
|
||||
|
||||
done?.();
|
||||
});
|
||||
|
||||
it("did create a version for a drive item", async done => {
|
||||
const item = await createItem();
|
||||
const fileUploadResponse = await e2e_createDocumentFile(platform);
|
||||
const fileUploadResult = deserialize<ResourceUpdateResponse<File>>(
|
||||
ResourceUpdateResponse,
|
||||
fileUploadResponse.body,
|
||||
);
|
||||
|
||||
const file_metadata = { external_id: fileUploadResult.resource.id };
|
||||
|
||||
await e2e_createVersion(platform, item.id, { filename: "file2", file_metadata });
|
||||
await e2e_createVersion(platform, item.id, { filename: "file3", file_metadata });
|
||||
await e2e_createVersion(platform, item.id, { filename: "file4", file_metadata });
|
||||
|
||||
const fetchItemResponse = await e2e_getDocument(platform, item.id);
|
||||
const fetchItemResult = deserialize<DriveItemDetailsMockClass>(
|
||||
DriveItemDetailsMockClass,
|
||||
fetchItemResponse.body,
|
||||
);
|
||||
|
||||
expect(fetchItemResult.versions).toHaveLength(4);
|
||||
|
||||
done?.();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { DriveFile } from "../../../src/services/documents/entities/drive-file";
|
||||
import { FileVersion } from "../../../src/services/documents/entities/file-version";
|
||||
import { TestPlatform } from "../setup";
|
||||
import formAutoContent from "form-auto-content";
|
||||
import fs from "fs";
|
||||
|
||||
const url = "/internal/services/documents/v1";
|
||||
|
||||
export const e2e_createDocument = async (
|
||||
platform: TestPlatform,
|
||||
item: Partial<DriveFile>,
|
||||
version: Partial<FileVersion>,
|
||||
) => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/item`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload: {
|
||||
item,
|
||||
version,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const e2e_getDocument = async (platform: TestPlatform, id: string | "root" | "trash") => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const e2e_deleteDocument = async (platform: TestPlatform, id: string | "root" | "trash") => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const e2e_updateDocument = async (
|
||||
platform: TestPlatform,
|
||||
id: string | "root" | "trash",
|
||||
item: Partial<DriveFile>,
|
||||
) => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload: item,
|
||||
});
|
||||
};
|
||||
|
||||
export const e2e_searchDocument = async (
|
||||
platform: TestPlatform,
|
||||
payload: Record<string, string>,
|
||||
) => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/search`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export const e2e_createVersion = async (
|
||||
platform: TestPlatform,
|
||||
id: string,
|
||||
payload: Partial<FileVersion>,
|
||||
) => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/item/${id}/version`,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
};
|
||||
|
||||
export const e2e_createDocumentFile = async (platform: TestPlatform) => {
|
||||
const filePath = `${__dirname}/assets/test.txt`;
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const form = formAutoContent({ file: fs.createReadStream(filePath) });
|
||||
form.headers["authorization"] = `Bearer ${token}`;
|
||||
|
||||
return await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `/internal/services/files/v1/companies/${platform.workspace.company_id}/files`,
|
||||
...form,
|
||||
});
|
||||
};
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
Binary file not shown.
@@ -0,0 +1,198 @@
|
||||
%PDF-1.3
|
||||
%âãÏÓ
|
||||
|
||||
1 0 obj
|
||||
<<
|
||||
/Type /Catalog
|
||||
/Outlines 2 0 R
|
||||
/Pages 3 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
2 0 obj
|
||||
<<
|
||||
/Type /Outlines
|
||||
/Count 0
|
||||
>>
|
||||
endobj
|
||||
|
||||
3 0 obj
|
||||
<<
|
||||
/Type /Pages
|
||||
/Count 2
|
||||
/Kids [ 4 0 R 6 0 R ]
|
||||
>>
|
||||
endobj
|
||||
|
||||
4 0 obj
|
||||
<<
|
||||
/Type /Page
|
||||
/Parent 3 0 R
|
||||
/Resources <<
|
||||
/Font <<
|
||||
/F1 9 0 R
|
||||
>>
|
||||
/ProcSet 8 0 R
|
||||
>>
|
||||
/MediaBox [0 0 612.0000 792.0000]
|
||||
/Contents 5 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
5 0 obj
|
||||
<< /Length 1074 >>
|
||||
stream
|
||||
2 J
|
||||
BT
|
||||
0 0 0 rg
|
||||
/F1 0027 Tf
|
||||
57.3750 722.2800 Td
|
||||
( A Simple PDF File ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 688.6080 Td
|
||||
( This is a small demonstration .pdf file - ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 664.7040 Td
|
||||
( just for use in the Virtual Mechanics tutorials. More text. And more ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 652.7520 Td
|
||||
( text. And more text. And more text. And more text. ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 628.8480 Td
|
||||
( And more text. And more text. And more text. And more text. And more ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 616.8960 Td
|
||||
( text. And more text. Boring, zzzzz. And more text. And more text. And ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 604.9440 Td
|
||||
( more text. And more text. And more text. And more text. And more text. ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 592.9920 Td
|
||||
( And more text. And more text. ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 569.0880 Td
|
||||
( And more text. And more text. And more text. And more text. And more ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 557.1360 Td
|
||||
( text. And more text. And more text. Even more. Continued on page 2 ...) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
|
||||
6 0 obj
|
||||
<<
|
||||
/Type /Page
|
||||
/Parent 3 0 R
|
||||
/Resources <<
|
||||
/Font <<
|
||||
/F1 9 0 R
|
||||
>>
|
||||
/ProcSet 8 0 R
|
||||
>>
|
||||
/MediaBox [0 0 612.0000 792.0000]
|
||||
/Contents 7 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
7 0 obj
|
||||
<< /Length 676 >>
|
||||
stream
|
||||
2 J
|
||||
BT
|
||||
0 0 0 rg
|
||||
/F1 0027 Tf
|
||||
57.3750 722.2800 Td
|
||||
( Simple PDF File 2 ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 688.6080 Td
|
||||
( ...continued from page 1. Yet more text. And more text. And more text. ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 676.6560 Td
|
||||
( And more text. And more text. And more text. And more text. And more ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 664.7040 Td
|
||||
( text. Oh, how boring typing this stuff. But not as boring as watching ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 652.7520 Td
|
||||
( paint dry. And more text. And more text. And more text. And more text. ) Tj
|
||||
ET
|
||||
BT
|
||||
/F1 0010 Tf
|
||||
69.2500 640.8000 Td
|
||||
( Boring. More, a little more text. The end, and just as well. ) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
|
||||
8 0 obj
|
||||
[/PDF /Text]
|
||||
endobj
|
||||
|
||||
9 0 obj
|
||||
<<
|
||||
/Type /Font
|
||||
/Subtype /Type1
|
||||
/Name /F1
|
||||
/BaseFont /Helvetica
|
||||
/Encoding /WinAnsiEncoding
|
||||
>>
|
||||
endobj
|
||||
|
||||
10 0 obj
|
||||
<<
|
||||
/Creator (Rave \(http://www.nevrona.com/rave\))
|
||||
/Producer (Nevrona Designs)
|
||||
/CreationDate (D:20060301072826)
|
||||
>>
|
||||
endobj
|
||||
|
||||
xref
|
||||
0 11
|
||||
0000000000 65535 f
|
||||
0000000019 00000 n
|
||||
0000000093 00000 n
|
||||
0000000147 00000 n
|
||||
0000000222 00000 n
|
||||
0000000390 00000 n
|
||||
0000001522 00000 n
|
||||
0000001690 00000 n
|
||||
0000002423 00000 n
|
||||
0000002456 00000 n
|
||||
0000002574 00000 n
|
||||
|
||||
trailer
|
||||
<<
|
||||
/Size 11
|
||||
/Root 1 0 R
|
||||
/Info 10 0 R
|
||||
>>
|
||||
|
||||
startxref
|
||||
2714
|
||||
%%EOF
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.7 KiB |
Binary file not shown.
@@ -0,0 +1,72 @@
|
||||
import "reflect-metadata";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import fs from "fs";
|
||||
import { File } from "../../../src/services/files/entities/file";
|
||||
import { deserialize } from "class-transformer";
|
||||
import formAutoContent from "form-auto-content";
|
||||
|
||||
describe.skip("The Files feature", () => {
|
||||
const url = "/internal/services/files/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeAll(async () => {
|
||||
platform = await init({
|
||||
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async done => {
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
done();
|
||||
});
|
||||
|
||||
describe("On user send files", () => {
|
||||
const files = [
|
||||
"assets/sample.png",
|
||||
"assets/sample.gif",
|
||||
"assets/sample.pdf",
|
||||
"assets/sample.doc",
|
||||
"assets/sample.zip",
|
||||
"assets/sample.mp4",
|
||||
].map(p => `${__dirname}/${p}`);
|
||||
const thumbnails = [1, 1, 2, 5, 0, 1];
|
||||
|
||||
it("should save file and generate previews", async done => {
|
||||
for (const i in files) {
|
||||
const file = files[i];
|
||||
|
||||
const form = formAutoContent({ file: fs.createReadStream(file) });
|
||||
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
|
||||
|
||||
const filesUploadRaw = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
|
||||
...form,
|
||||
});
|
||||
const filesUpload: ResourceUpdateResponse<File> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
filesUploadRaw.body,
|
||||
);
|
||||
|
||||
expect(filesUpload.resource.id).not.toBeFalsy();
|
||||
expect(filesUpload.resource.encryption_key).toBeFalsy(); //This must not be disclosed
|
||||
expect(filesUpload.resource.thumbnails.length).toBe(thumbnails[i]);
|
||||
|
||||
for (const thumb of filesUpload.resource.thumbnails) {
|
||||
const thumbnails = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/files/${filesUpload.resource.id}/thumbnails/${thumb.index}`,
|
||||
});
|
||||
expect(thumbnails.statusCode).toBe(200);
|
||||
}
|
||||
}
|
||||
|
||||
done();
|
||||
}, 120000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import "reflect-metadata";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { createMessage, createParticipant, e2e_createThread } from "./utils";
|
||||
import { MessageFile } from "../../../src/services/messages/entities/message-files";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import fs from "fs";
|
||||
import formAutoContent from "form-auto-content";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import uuid from "node-uuid";
|
||||
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
import User from "../../../src/services/user/entities/user";
|
||||
import { WorkspaceExecutionContext } from "../../../src/services/channels/types";
|
||||
|
||||
describe("Search files", () => {
|
||||
const filesUrl = "/internal/services/files/v1";
|
||||
const messagesUrl = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeAll(async () => {
|
||||
platform = await init({
|
||||
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
|
||||
});
|
||||
await platform.database.getConnector().drop();
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterAll(async done => {
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
done();
|
||||
});
|
||||
|
||||
const files = [
|
||||
"../files/assets/sample.png",
|
||||
"../files/assets/sample.gif",
|
||||
"../files/assets/sample.pdf",
|
||||
"../files/assets/sample.doc",
|
||||
"../files/assets/sample.zip",
|
||||
].map(p => `${__dirname}/${p}`);
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
it("should return uploaded files", async done => {
|
||||
let channel = channelUtils.getChannel();
|
||||
channel = (await gr.services.channels.channels.save(channel, {}, getContext())).entity;
|
||||
const channelId = channel.id;
|
||||
|
||||
const uploadedFiles = [];
|
||||
for (const i in files) {
|
||||
const file = files[i];
|
||||
|
||||
const form = formAutoContent({ file: fs.createReadStream(file) });
|
||||
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
|
||||
|
||||
const uploadedFile = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
|
||||
...form,
|
||||
});
|
||||
|
||||
const resource = uploadedFile.json().resource;
|
||||
|
||||
const messageFile: Partial<MessageFile> = {
|
||||
id: uuid.v1(),
|
||||
company_id: platform.workspace.company_id,
|
||||
metadata: {
|
||||
source: "internal",
|
||||
external_id: {
|
||||
company_id: platform.workspace.company_id,
|
||||
id: resource.id,
|
||||
},
|
||||
...resource.metadata,
|
||||
},
|
||||
};
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channelId,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Some message", files: [messageFile] }),
|
||||
);
|
||||
|
||||
uploadedFiles.push(uploadedFile.json().resource);
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
|
||||
let resources = await search("sample");
|
||||
expect(resources.length).toEqual(5);
|
||||
|
||||
resources = await search("sample", { extension: "png" });
|
||||
expect(resources.length).toEqual(1);
|
||||
|
||||
resources = await search("sample", { is_file: true });
|
||||
expect(resources.length).toEqual(3);
|
||||
|
||||
resources = await search("sample", { is_media: true });
|
||||
expect(resources.length).toEqual(2);
|
||||
|
||||
resources = await search("sam");
|
||||
expect(resources.length).toEqual(5);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
async function search(
|
||||
searchString: string,
|
||||
options?: {
|
||||
company_id?: string;
|
||||
workspace_id?: string;
|
||||
channel_id?: string;
|
||||
limit?: number;
|
||||
sender?: string;
|
||||
is_file?: boolean;
|
||||
is_media?: boolean;
|
||||
extension?: string;
|
||||
},
|
||||
): Promise<any[]> {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
|
||||
const query: any = options || {};
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files/search`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
...query,
|
||||
q: searchString,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const json = response.json();
|
||||
expect(json).toMatchObject({ resources: expect.any(Array) });
|
||||
const resources = json.resources;
|
||||
return resources;
|
||||
}
|
||||
});
|
||||
|
||||
function getContext(platform: TestPlatform) {
|
||||
return {
|
||||
company: { id: platform.workspace.company_id },
|
||||
user: { id: platform.currentUser.id },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import "reflect-metadata";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { Thread } from "../../../src/services/messages/entities/threads";
|
||||
import { createMessage, e2e_createThread } from "./utils";
|
||||
import { MessageFile } from "../../../src/services/messages/entities/message-files";
|
||||
import { Message } from "../../../src/services/messages/entities/messages";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import fs from "fs";
|
||||
import formAutoContent from "form-auto-content";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import uuid, { v1 } from "node-uuid";
|
||||
|
||||
describe("The Messages Files feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"applications",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"files",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
describe("On user send files", () => {
|
||||
it("did add the files when full information is given (external source)", async done => {
|
||||
const file: MessageFile = {
|
||||
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
|
||||
company_id: "",
|
||||
created_at: 0,
|
||||
id: "",
|
||||
metadata: {
|
||||
source: "linshare",
|
||||
external_id: "1234",
|
||||
name: "My LinShare File",
|
||||
thumbnails: [],
|
||||
},
|
||||
};
|
||||
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[],
|
||||
createMessage({ text: "Some message", files: [file] }),
|
||||
);
|
||||
const result: ResourceUpdateResponse<Thread & { message: Message }> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(result.resource.message.files.length).toBe(1);
|
||||
expect(result.resource.message.files[0].id).not.toBeFalsy();
|
||||
expect(result.resource.message.files[0].message_id).not.toBeFalsy();
|
||||
expect(result.resource.message.files[0].metadata.external_id).toBe("1234");
|
||||
expect(result.resource.message.files[0].metadata.source).toBe("linshare");
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("did not deduplicate files", async done => {
|
||||
const file: MessageFile = {
|
||||
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
|
||||
company_id: "",
|
||||
created_at: 0,
|
||||
id: "",
|
||||
metadata: {
|
||||
source: "linshare",
|
||||
external_id: "1234",
|
||||
name: "My LinShare File",
|
||||
thumbnails: [],
|
||||
},
|
||||
};
|
||||
|
||||
const file2: MessageFile = {
|
||||
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
|
||||
company_id: "",
|
||||
created_at: 0,
|
||||
id: "",
|
||||
metadata: {
|
||||
source: "linshare2",
|
||||
external_id: "5678",
|
||||
name: "My LinShare 2 File",
|
||||
thumbnails: [],
|
||||
},
|
||||
};
|
||||
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[],
|
||||
createMessage({ text: "Some message", files: [file] }),
|
||||
);
|
||||
const result: ResourceUpdateResponse<Thread & { message: Message }> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
const message = result.resource.message;
|
||||
const firstFileId = message.files[0].id;
|
||||
|
||||
message.files.push(file2);
|
||||
|
||||
const messageUpdatedRaw = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads/${message.thread_id}/messages/${message.id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${await platform.auth.getJWTToken()}`,
|
||||
},
|
||||
payload: {
|
||||
resource: message,
|
||||
},
|
||||
});
|
||||
const messageUpdated: ResourceUpdateResponse<Message> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
messageUpdatedRaw.body,
|
||||
);
|
||||
|
||||
expect(messageUpdated.resource.files.length).toBe(2);
|
||||
expect(messageUpdated.resource.files.filter(f => f.id === firstFileId).length).toBe(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("List user files", () => {
|
||||
const filesUrl = "/internal/services/files/v1";
|
||||
const messagesUrl = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeAll(async () => {
|
||||
platform = await init({
|
||||
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
|
||||
});
|
||||
await platform.database.getConnector().drop();
|
||||
});
|
||||
|
||||
afterAll(async done => {
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
done();
|
||||
});
|
||||
|
||||
const files = [
|
||||
"../files/assets/sample.png",
|
||||
"../files/assets/sample.gif",
|
||||
"../files/assets/sample.pdf",
|
||||
"../files/assets/sample.doc",
|
||||
"../files/assets/sample.zip",
|
||||
].map(p => `${__dirname}/${p}`);
|
||||
|
||||
it("should return uploaded files", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
|
||||
const uploadedFiles = [];
|
||||
|
||||
for (const i in files) {
|
||||
const file = files[i];
|
||||
|
||||
const form = formAutoContent({ file: fs.createReadStream(file) });
|
||||
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
|
||||
|
||||
const uploadedFile = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
|
||||
...form,
|
||||
});
|
||||
|
||||
expect(uploadedFile.statusCode).toBe(200);
|
||||
|
||||
const resource = uploadedFile.json().resource;
|
||||
|
||||
const messageFile: MessageFile = {
|
||||
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
|
||||
created_at: 0,
|
||||
id: uuid.v1(),
|
||||
company_id: platform.workspace.company_id,
|
||||
metadata: {
|
||||
source: "internal",
|
||||
external_id: {
|
||||
company_id: platform.workspace.company_id,
|
||||
id: resource.id,
|
||||
},
|
||||
...resource.metadata,
|
||||
},
|
||||
};
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[],
|
||||
createMessage({ text: "Some message", files: [messageFile] }),
|
||||
);
|
||||
|
||||
uploadedFiles.push(uploadedFile.json().resource);
|
||||
}
|
||||
|
||||
function checkResource(resource) {
|
||||
expect(resource).toMatchObject({
|
||||
company_id: expect.any(String),
|
||||
id: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
metadata: expect.any(Object),
|
||||
});
|
||||
}
|
||||
|
||||
let response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_upload&limit=3`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
let resources = response.json().resources;
|
||||
expect(resources.length).toBe(3);
|
||||
|
||||
resources.forEach(checkResource);
|
||||
|
||||
const nextPageToken = response.json().next_page_token;
|
||||
|
||||
response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_upload&page_token=${nextPageToken}limit=100`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
resources = response.json().resources;
|
||||
expect(resources.length).toBe(5);
|
||||
|
||||
expect(response.json().resources[0]).toMatchObject({
|
||||
company_id: expect.any(String),
|
||||
id: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
metadata: expect.any(Object),
|
||||
user: expect.any(Object),
|
||||
context: expect.any(Object),
|
||||
});
|
||||
|
||||
resources.forEach(checkResource);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should return downloaded files", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: v1() });
|
||||
const uploadedFiles = [];
|
||||
for (const i in files) {
|
||||
const file = files[i];
|
||||
|
||||
const form = formAutoContent({ file: fs.createReadStream(file) });
|
||||
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
|
||||
|
||||
const uploadedFile = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${filesUrl}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
|
||||
...form,
|
||||
});
|
||||
|
||||
const resource = uploadedFile.json().resource;
|
||||
|
||||
const messageFile: MessageFile = {
|
||||
cache: { channel_id: "", company_id: "", user_id: "", workspace_id: "" },
|
||||
created_at: 0,
|
||||
id: uuid.v1(),
|
||||
company_id: platform.workspace.company_id,
|
||||
metadata: {
|
||||
source: "internal",
|
||||
external_id: {
|
||||
company_id: platform.workspace.company_id,
|
||||
id: resource.id,
|
||||
},
|
||||
...resource.metadata,
|
||||
},
|
||||
};
|
||||
|
||||
const thread = await e2e_createThread(
|
||||
platform,
|
||||
[],
|
||||
createMessage({ text: "Some message", files: [messageFile] }),
|
||||
);
|
||||
|
||||
uploadedFiles.push(uploadedFile.json().resource);
|
||||
|
||||
await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${messagesUrl}/companies/${platform.workspace.company_id}/threads/${
|
||||
thread.json().resource.message.thread_id
|
||||
}/messages/${thread.json().resource.message.id}/download/${
|
||||
thread.json().resource.message.files[0].id
|
||||
}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${messagesUrl}/companies/${platform.workspace.company_id}/files?type=user_download`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(response.json().resources.length).toBe(5);
|
||||
|
||||
expect(response.json().resources[0]).toMatchObject({
|
||||
company_id: expect.any(String),
|
||||
id: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
metadata: expect.any(Object),
|
||||
user: expect.any(Object),
|
||||
context: expect.any(Object),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
function getContext(platform: TestPlatform) {
|
||||
return {
|
||||
company: { id: platform.workspace.company_id },
|
||||
user: { id: platform.currentUser.id },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import {
|
||||
ResourceListResponse,
|
||||
ResourceUpdateResponse,
|
||||
User,
|
||||
Workspace,
|
||||
} from "../../../src/utils/types";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { ParticipantObject, Thread } from "../../../src/services/messages/entities/threads";
|
||||
import {
|
||||
createMessage,
|
||||
createParticipant,
|
||||
e2e_createChannel,
|
||||
e2e_createMessage,
|
||||
e2e_createThread,
|
||||
} from "./utils";
|
||||
import { Message } from "../../../src/services/messages/entities/messages";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { MessageWithReplies } from "../../../src/services/messages/types";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
import { ChannelVisibility, WorkspaceExecutionContext } from "../../../src/services/channels/types";
|
||||
import { ChannelSaveOptions } from "../../../src/services/channels/web/types";
|
||||
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
|
||||
|
||||
describe("The Messages feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
let testDbService: TestDbService;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"applications",
|
||||
"user",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"messages",
|
||||
"files",
|
||||
"auth",
|
||||
"search",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
await gr.database.getConnector().drop();
|
||||
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
describe("On user use messages in a thread", () => {
|
||||
it("should create a message in a thread", async () => {
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[],
|
||||
createMessage({ text: "Initial thread message" }),
|
||||
);
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
const threadId = result.resource.id;
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 1" }));
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 2" }));
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const listResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads/${threadId}/messages`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const listResult: ResourceListResponse<Thread> = deserialize(
|
||||
ResourceListResponse,
|
||||
listResponse.body,
|
||||
);
|
||||
|
||||
expect(listResponse.statusCode).toBe(200);
|
||||
expect(listResult.resources.length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Inbox", () => {
|
||||
it("Should get recent user messages", async done => {
|
||||
const directChannelIn = channelUtils.getDirectChannel();
|
||||
const members = [platform.currentUser.id, uuidv1()];
|
||||
const directWorkspace: Workspace = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
gr.services.channels.channels.save<ChannelSaveOptions>(
|
||||
directChannelIn,
|
||||
{
|
||||
members,
|
||||
},
|
||||
{ ...getContext(), ...{ workspace: directWorkspace } },
|
||||
),
|
||||
]);
|
||||
|
||||
const recipient: ParticipantObject = {
|
||||
created_at: 0,
|
||||
created_by: "",
|
||||
type: "channel",
|
||||
company_id: directChannelIn.company_id,
|
||||
workspace_id: "direct",
|
||||
id: directChannelIn.id,
|
||||
};
|
||||
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[recipient],
|
||||
createMessage({ text: `Initial thread message ${i}` }),
|
||||
);
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
const threadId = result.resource.id;
|
||||
|
||||
const replies = [];
|
||||
for (let j = 0; j < 3; j++) {
|
||||
replies.push(
|
||||
e2e_createMessage(
|
||||
platform,
|
||||
threadId,
|
||||
createMessage({ text: `Reply ${j} to message ${i}` }),
|
||||
),
|
||||
);
|
||||
}
|
||||
await Promise.all(replies);
|
||||
}
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: members[0] });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/inbox?limit=5`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toEqual(200);
|
||||
|
||||
const inbox: ResourceListResponse<MessageWithReplies> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(inbox.resources.length).toEqual(5);
|
||||
|
||||
for (const resource of inbox.resources) {
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
thread_id: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
updated_at: expect.any(Number),
|
||||
user_id: platform.currentUser.id,
|
||||
application_id: null,
|
||||
text: expect.any(String),
|
||||
cache: {
|
||||
company_id: directChannelIn.company_id,
|
||||
channel_id: directChannelIn.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { createMessage, e2e_createChannel, e2e_createMessage, e2e_createThread } from "./utils";
|
||||
import { ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { ParticipantObject, Thread } from "../../../src/services/messages/entities/threads";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { Channel } from "../../../src/services/channels/entities";
|
||||
import { ChannelUtils, get as getChannelUtils } from "../channels/utils";
|
||||
import { MessageFile } from "../../../src/services/messages/entities/message-files";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The /messages API", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"search",
|
||||
"message-queue",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"user",
|
||||
"auth",
|
||||
"applications",
|
||||
"storage",
|
||||
"counter",
|
||||
"workspaces",
|
||||
"console",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
await platform.database.getConnector().drop();
|
||||
channelUtils = getChannelUtils(platform);
|
||||
|
||||
const testDbService = new TestDbService(platform);
|
||||
await testDbService.createCompany(platform.workspace.company_id);
|
||||
|
||||
const workspacePk = {
|
||||
id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
|
||||
const workspacePk2 = {
|
||||
id: uuidv1(),
|
||||
company_id: uuidv1(),
|
||||
};
|
||||
await testDbService.createWorkspace(workspacePk);
|
||||
|
||||
const user = await testDbService.createUser([workspacePk], {});
|
||||
|
||||
platform.currentUser.id = user.id;
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
platform && (await platform.tearDown());
|
||||
platform = null;
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("The GET /messages/?search=... route", () => {
|
||||
it("Should find the searched messages", async done => {
|
||||
// await testDbService.createWorkspace(workspacePk2);
|
||||
|
||||
const channel = await createChannel();
|
||||
|
||||
const participant = {
|
||||
type: "channel",
|
||||
id: channel.id,
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
} as ParticipantObject;
|
||||
|
||||
const firstThreadId = await createThread("First thread", [participant]);
|
||||
await createReply(firstThreadId, "First reply of first thread");
|
||||
await createReply(firstThreadId, "Second reply of first thread");
|
||||
|
||||
const secondThreadId = await createThread("Another thread", [participant]);
|
||||
await createReply(secondThreadId, "First reply of second thread");
|
||||
await createReply(secondThreadId, "Second reply of second thread is also a message");
|
||||
|
||||
//Wait for indexation to happen
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
|
||||
let resources = await search("Reply");
|
||||
expect(resources.length).toEqual(4);
|
||||
|
||||
resources = await search("fdfsd");
|
||||
expect(resources.length).toEqual(0);
|
||||
|
||||
resources = await search("first");
|
||||
expect(resources.length).toEqual(4);
|
||||
|
||||
resources = await search("second");
|
||||
expect(resources.length).toEqual(3);
|
||||
|
||||
resources = await search("another");
|
||||
expect(resources.length).toEqual(1);
|
||||
|
||||
resources = await search("also");
|
||||
expect(resources.length).toEqual(1);
|
||||
|
||||
resources = await search("of");
|
||||
expect(resources.length).toEqual(4);
|
||||
|
||||
resources = await search("a");
|
||||
|
||||
//sleep 1s
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
|
||||
expect(resources.length).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
it("Filter out messages from channels we are not member of", async done => {
|
||||
const anotherUserId = uuidv1();
|
||||
const channel = await e2e_createChannel(platform, [platform.currentUser.id, anotherUserId]);
|
||||
const anotherChannel = await e2e_createChannel(platform, [anotherUserId], anotherUserId); //Test user is not the owner
|
||||
|
||||
const participant = {
|
||||
type: "channel",
|
||||
id: channel.resource.id,
|
||||
company_id: channel.resource.company_id,
|
||||
workspace_id: channel.resource.workspace_id,
|
||||
} as ParticipantObject;
|
||||
|
||||
const participant2 = {
|
||||
type: "channel",
|
||||
id: anotherChannel.resource.id,
|
||||
company_id: anotherChannel.resource.company_id,
|
||||
workspace_id: anotherChannel.resource.workspace_id,
|
||||
} as ParticipantObject;
|
||||
|
||||
const file = new MessageFile();
|
||||
file.metadata = { external_id: undefined, source: undefined, name: "test" };
|
||||
|
||||
const firstThreadId = await createThread("Filtered thread", [participant]);
|
||||
await createReply(firstThreadId, "Filtered message 1-1");
|
||||
await createReply(firstThreadId, "Filtered message 1-2");
|
||||
await createReply(firstThreadId, "Filtered message 1-3");
|
||||
await createReply(firstThreadId, "Filtered message 1-4", { files: [file] });
|
||||
|
||||
const secondThreadId = await createThread("Filtered thread 2", [participant2], anotherUserId);
|
||||
await createReply(secondThreadId, "Filtered message 2-1");
|
||||
await createReply(secondThreadId, "Filtered message 2-2");
|
||||
await createReply(secondThreadId, "Filtered message 2-3");
|
||||
await createReply(secondThreadId, "Filtered message 2-4");
|
||||
|
||||
const thirdThreadId = await createThread("Filtered thread 3", [participant]);
|
||||
await createReply(thirdThreadId, "Filtered message 3-1");
|
||||
await createReply(thirdThreadId, "Filtered message 3-2", { userId: anotherUserId });
|
||||
await createReply(thirdThreadId, "Filtered message 3-3", { userId: anotherUserId });
|
||||
await createReply(thirdThreadId, "Filtered message 3-4", {
|
||||
userId: anotherUserId,
|
||||
files: [file],
|
||||
});
|
||||
|
||||
//Wait for indexation to happen
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
|
||||
// no limit
|
||||
const resources0 = await search("Filtered", { limit: 10000 });
|
||||
expect(resources0.length).toEqual(10);
|
||||
|
||||
const resources = await search("Filtered", { limit: 9 });
|
||||
expect(resources.length).toEqual(9);
|
||||
|
||||
// check for the empty result set
|
||||
const resources2 = await search("Nothing", { limit: 10 });
|
||||
expect(resources2.length).toEqual(0);
|
||||
|
||||
// check for the user
|
||||
const resources3 = await search("Filtered", { sender: anotherUserId });
|
||||
expect(resources3.length).toEqual(3);
|
||||
|
||||
// check for the files
|
||||
const resources4 = await search("Filtered", { has_files: true });
|
||||
expect(resources4.length).toEqual(2);
|
||||
|
||||
// check for the user and files
|
||||
const resources5 = await search("Filtered", { sender: anotherUserId, has_files: true });
|
||||
expect(resources5.length).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
async function createChannel(userId = platform.currentUser.id): Promise<Channel> {
|
||||
const channel = channelUtils.getChannel(userId);
|
||||
const creationResult = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext({ id: userId }),
|
||||
);
|
||||
|
||||
return creationResult.entity;
|
||||
}
|
||||
|
||||
async function createThread(text, participants: ParticipantObject[], owner?: string) {
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
participants,
|
||||
createMessage({ text: text, user_id: owner }),
|
||||
owner,
|
||||
);
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
return result.resource.id;
|
||||
}
|
||||
|
||||
async function createReply(threadId, text, options?: { userId?: string; files?: MessageFile[] }) {
|
||||
const cr = options?.userId ? { currentUser: { id: options?.userId } } : undefined;
|
||||
|
||||
const message = { text, ...(options?.files ? { files: options.files } : {}) };
|
||||
|
||||
return e2e_createMessage(platform, threadId, createMessage(message, cr as TestPlatform));
|
||||
}
|
||||
|
||||
async function search(
|
||||
searchString: string,
|
||||
options?: {
|
||||
company_id?: string;
|
||||
workspace_id?: string;
|
||||
channel_id?: string;
|
||||
limit?: number;
|
||||
sender?: string;
|
||||
has_files?: boolean;
|
||||
},
|
||||
): Promise<any[]> {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
|
||||
const query: any = options || {};
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
// url: `${url}/companies/${platform.workspace.company_id}/woskpaces/`,
|
||||
url: `${url}/companies/${platform.workspace.company_id}/search`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
...query,
|
||||
q: searchString,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const json = response.json();
|
||||
expect(json).toMatchObject({ resources: expect.any(Array) });
|
||||
const resources = json.resources;
|
||||
return resources;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { v1 as uuidv1, v4 as uuidv4 } from "uuid";
|
||||
import { Thread } from "../../../src/services/messages/entities/threads";
|
||||
import { createMessage, createParticipant, e2e_createThread } from "./utils";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The Messages Threads feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"applications",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"files",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
describe("On user manage threads", () => {
|
||||
it("should create new thread", async done => {
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage(
|
||||
{
|
||||
text: "Hello!",
|
||||
},
|
||||
platform,
|
||||
),
|
||||
);
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource?.created_by).toBe(platform.currentUser.id);
|
||||
expect(result.resource.participants.length).toBe(1);
|
||||
expect(result.resource.participants[0]).toMatchObject({
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
created_by: platform.currentUser.id,
|
||||
});
|
||||
expect(result.resource.participants[0].created_at).toBeDefined();
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should enforce requester in thread participants", async done => {
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "user",
|
||||
id: uuidv1(),
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage(
|
||||
{
|
||||
text: "Hello!",
|
||||
},
|
||||
platform,
|
||||
),
|
||||
);
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource).toMatchObject({
|
||||
created_by: platform.currentUser.id,
|
||||
});
|
||||
expect(result.resource.participants.length).toBe(2);
|
||||
expect(
|
||||
result.resource.participants.filter(p => p.id === platform.currentUser.id)[0],
|
||||
).toMatchObject({
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should update thread participants when add participant", async done => {
|
||||
//Create thread
|
||||
const thread = await gr.services.messages.threads.save(
|
||||
{
|
||||
id: undefined,
|
||||
participants: [
|
||||
{
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
company_id: platform.workspace.company_id,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
message: createMessage(
|
||||
{
|
||||
text: "Hello!",
|
||||
},
|
||||
platform,
|
||||
),
|
||||
},
|
||||
getContext(platform),
|
||||
);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads/${thread.entity.id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {},
|
||||
options: {
|
||||
participants: {
|
||||
add: [
|
||||
{
|
||||
type: "user",
|
||||
id: uuidv1(),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource.participants.length).toBe(2);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should update thread participants when remove participant", async done => {
|
||||
//Create thread
|
||||
const thread = await gr.services.messages.threads.save(
|
||||
{
|
||||
id: undefined,
|
||||
participants: [
|
||||
{
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
company_id: platform.workspace.company_id,
|
||||
},
|
||||
{
|
||||
type: "channel",
|
||||
id: uuidv4(),
|
||||
workspace_id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
message: createMessage(
|
||||
{
|
||||
text: "Hello!",
|
||||
},
|
||||
platform,
|
||||
),
|
||||
},
|
||||
getContext(platform),
|
||||
);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads/${thread.entity.id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {},
|
||||
options: {
|
||||
participants: {
|
||||
remove: [
|
||||
{
|
||||
type: "user",
|
||||
id: platform.currentUser.id,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource.participants.length).toBe(1);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getContext(platform: TestPlatform) {
|
||||
return {
|
||||
company: { id: platform.workspace.company_id },
|
||||
user: { id: platform.currentUser.id },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import io from "socket.io-client";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The Bookmarks Realtime feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
let socket: SocketIOClient.Socket;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"files",
|
||||
"user",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"messages",
|
||||
"applications",
|
||||
"auth",
|
||||
"search",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
});
|
||||
|
||||
function connect() {
|
||||
socket = io.connect("http://localhost:3000", { path: "/socket" });
|
||||
socket.connect();
|
||||
}
|
||||
|
||||
describe("On bookmark creation", () => {
|
||||
it("should notify the client", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
await gr.services.messages.userBookmarks.save(
|
||||
{
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmarksaved",
|
||||
id: undefined,
|
||||
},
|
||||
getContext(platform),
|
||||
);
|
||||
});
|
||||
socket.on("realtime:resource", (event: any) => {
|
||||
expect(event.type).toEqual("user_message_bookmark");
|
||||
expect(event.action).toEqual("saved");
|
||||
expect(event.resource.name).toEqual("mybookmarksaved");
|
||||
done();
|
||||
});
|
||||
socket.emit("realtime:join", {
|
||||
name: `/companies/${platform.workspace.company_id}/messages/bookmarks`,
|
||||
token: roomToken,
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("On bookmark removal", () => {
|
||||
it("should notify the client", async done => {
|
||||
const instance = await gr.services.messages.userBookmarks.save(
|
||||
{
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
id: undefined,
|
||||
},
|
||||
getContext(platform),
|
||||
);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
|
||||
connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: jwtToken })
|
||||
.on("authenticated", () => {
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", async () => {
|
||||
await gr.services.messages.userBookmarks.delete(
|
||||
{
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
id: instance.entity.id,
|
||||
},
|
||||
getContext(platform),
|
||||
);
|
||||
});
|
||||
socket.on("realtime:resource", (event: any) => {
|
||||
expect(event.type).toEqual("user_message_bookmark");
|
||||
expect(event.action).toEqual("deleted");
|
||||
done();
|
||||
});
|
||||
socket.emit("realtime:join", {
|
||||
name: `/companies/${platform.workspace.company_id}/messages/bookmarks`,
|
||||
token: roomToken,
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getContext(platform: TestPlatform) {
|
||||
return {
|
||||
company: { id: platform.workspace.company_id },
|
||||
user: { id: platform.currentUser.id },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { UserMessageBookmark } from "../../../src/services/messages/entities/user-message-bookmarks";
|
||||
import { ResourceListResponse, ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The Messages User Bookmarks feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"files",
|
||||
"storage",
|
||||
"applications",
|
||||
"message-queue",
|
||||
"user",
|
||||
"search",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
describe("On user manage bookmmarks", () => {
|
||||
it("should create new bookmark", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
name: "mybookmark",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceUpdateResponse<UserMessageBookmark> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource).toMatchObject({
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
});
|
||||
|
||||
const context = getContext(platform);
|
||||
|
||||
const list = await gr.services.messages.userBookmarks.list({
|
||||
user_id: context.user.id,
|
||||
company_id: context.company.id,
|
||||
});
|
||||
expect(list.getEntities().length).toBe(1);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should prevent duplicated bookmark", async done => {
|
||||
// const uuid = uuidv4();
|
||||
|
||||
const context = getContext(platform);
|
||||
|
||||
const data = await gr.services.messages.userBookmarks.save(
|
||||
{
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
test: "123",
|
||||
},
|
||||
context,
|
||||
);
|
||||
const uuid = data.entity.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
name: "mybookmark",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceUpdateResponse<UserMessageBookmark> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resource).toMatchObject({
|
||||
id: uuid,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
});
|
||||
|
||||
const list = await gr.services.messages.userBookmarks.list({
|
||||
user_id: context.user.id,
|
||||
company_id: context.company.id,
|
||||
});
|
||||
expect(list.getEntities().length).toBe(1);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should remove bookmark", async done => {
|
||||
const id = uuidv4();
|
||||
const context = getContext(platform);
|
||||
|
||||
await gr.services.messages.userBookmarks.save(
|
||||
{
|
||||
id,
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
},
|
||||
context,
|
||||
);
|
||||
|
||||
let list = await gr.services.messages.userBookmarks.list({
|
||||
user_id: context.user.id,
|
||||
company_id: context.company.id,
|
||||
});
|
||||
expect(list.getEntities().length).toBe(1);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks/${id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
list = await gr.services.messages.userBookmarks.list({
|
||||
user_id: context.user.id,
|
||||
company_id: context.company.id,
|
||||
});
|
||||
expect(list.getEntities().length).toBe(0);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should list bookmarks", async done => {
|
||||
const context = getContext(platform);
|
||||
|
||||
await gr.services.messages.userBookmarks.save(
|
||||
{
|
||||
id: uuidv4(),
|
||||
company_id: platform.workspace.company_id,
|
||||
user_id: platform.currentUser.id,
|
||||
name: "mybookmark",
|
||||
},
|
||||
context,
|
||||
);
|
||||
|
||||
const list = await gr.services.messages.userBookmarks.list({
|
||||
user_id: context.user.id,
|
||||
company_id: context.company.id,
|
||||
});
|
||||
expect(list.getEntities().length).toBe(1);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/preferences/bookmarks`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const result: ResourceListResponse<UserMessageBookmark> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(result.resources.length).toBe(1);
|
||||
expect(result.resources[0].name).toBe("mybookmark");
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function getContext(platform: TestPlatform) {
|
||||
return {
|
||||
company: { id: platform.workspace.company_id },
|
||||
user: { id: platform.currentUser.id },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { ResourceListResponse, ResourceUpdateResponse } from "../../../src/utils/types";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { Thread } from "../../../src/services/messages/entities/threads";
|
||||
import {
|
||||
createMessage,
|
||||
createParticipant,
|
||||
e2e_createChannel,
|
||||
e2e_createMessage,
|
||||
e2e_createThread,
|
||||
} from "./utils";
|
||||
import { MessageWithReplies } from "../../../src/services/messages/types";
|
||||
|
||||
describe("The Messages feature", () => {
|
||||
const url = "/internal/services/messages/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"files",
|
||||
"applications",
|
||||
"message-queue",
|
||||
"user",
|
||||
"websocket",
|
||||
"messages",
|
||||
"auth",
|
||||
"search",
|
||||
"realtime",
|
||||
"channels",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await platform.tearDown();
|
||||
});
|
||||
|
||||
describe("On user use messages in channel view", () => {
|
||||
it("should create a message and retrieve it in channel view", async () => {
|
||||
const channel = await e2e_createChannel(platform, [platform.currentUser.id]);
|
||||
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channel.resource.id,
|
||||
workspace_id: channel.resource.workspace_id,
|
||||
company_id: channel.resource.company_id,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 1 message" }),
|
||||
);
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
const threadId = result.resource.id;
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 1" }));
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 2" }));
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channel.resource.id,
|
||||
workspace_id: channel.resource.workspace_id,
|
||||
company_id: channel.resource.company_id,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 2 message" }),
|
||||
);
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 3" }));
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channel.resource.id,
|
||||
workspace_id: channel.resource.workspace_id,
|
||||
company_id: channel.resource.company_id,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 3 message" }),
|
||||
);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const listResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${channel.resource.company_id}/workspaces/${channel.resource.workspace_id}/channels/${channel.resource.id}/feed?replies_per_thread=3&include_users=1`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const listResult: ResourceListResponse<MessageWithReplies> = deserialize(
|
||||
ResourceListResponse,
|
||||
listResponse.body,
|
||||
);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
expect(listResponse.statusCode).toBe(200);
|
||||
expect(listResult.resources.length).toBe(3);
|
||||
|
||||
expect(listResult.resources[0].text).toBe("Initial thread 2 message");
|
||||
expect(listResult.resources[1].text).toBe("Initial thread 1 message");
|
||||
expect(listResult.resources[2].text).toBe("Initial thread 3 message");
|
||||
|
||||
expect(listResult.resources[0].stats.replies).toBe(1);
|
||||
expect(listResult.resources[1].stats.replies).toBe(4); //Thread initial message + 3 replies
|
||||
expect(listResult.resources[2].stats.replies).toBe(1);
|
||||
|
||||
expect(listResult.resources[1].last_replies.length).toBe(3); //We requested 3 replies per posts
|
||||
expect(listResult.resources[1].last_replies[0].text).toBe("Reply 1"); //Check order is OK
|
||||
expect(listResult.resources[1].last_replies[2].text).toBe("Reply 3");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { deserialize } from "class-transformer";
|
||||
import {
|
||||
getInstance as getMessageInstance,
|
||||
Message,
|
||||
} from "../../../src/services/messages/entities/messages";
|
||||
import { ParticipantObject } from "../../../src/services/messages/entities/threads";
|
||||
import { Channel, ResourceCreateResponse } from "../../../src/utils/types";
|
||||
import { TestPlatform } from "../setup";
|
||||
|
||||
const url = "/internal/services/messages/v1";
|
||||
|
||||
export const e2e_createChannel = async (
|
||||
platform: TestPlatform,
|
||||
members: string[],
|
||||
owner?: string,
|
||||
) => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: owner || platform.currentUser.id });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `/internal/services/channels/v1/companies/${platform.workspace.company_id}/workspaces/direct/channels`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
options: {
|
||||
members,
|
||||
},
|
||||
resource: {
|
||||
description: "A direct channel description",
|
||||
visibility: "direct",
|
||||
},
|
||||
},
|
||||
});
|
||||
const channelCreateResult: ResourceCreateResponse<Channel> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
response.body,
|
||||
);
|
||||
return channelCreateResult;
|
||||
};
|
||||
|
||||
export const e2e_createThread = async (
|
||||
platform: TestPlatform,
|
||||
participants: ParticipantObject[],
|
||||
message: Message,
|
||||
owner?: string,
|
||||
) => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: owner || platform.currentUser.id });
|
||||
const res = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
participants: participants || [],
|
||||
},
|
||||
options: {
|
||||
message: message,
|
||||
},
|
||||
},
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
return res;
|
||||
};
|
||||
|
||||
export const e2e_createMessage = async (
|
||||
platform: TestPlatform,
|
||||
threadId: string,
|
||||
message: Message,
|
||||
) => {
|
||||
const jwtToken = await platform.auth.getJWTToken(
|
||||
message.user_id ? { sub: message.user_id } : undefined,
|
||||
);
|
||||
const res = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/threads/${threadId}/messages`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: message,
|
||||
},
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
return res;
|
||||
};
|
||||
|
||||
export const createMessage = (message: Partial<Message>, platform?: TestPlatform): Message => {
|
||||
return getMessageInstance({
|
||||
//Default values
|
||||
created_at: new Date().getTime(),
|
||||
user_id: platform?.currentUser.id || undefined,
|
||||
|
||||
...message,
|
||||
});
|
||||
};
|
||||
|
||||
export const createParticipant = (
|
||||
participant: Partial<ParticipantObject>,
|
||||
platform?: TestPlatform,
|
||||
): ParticipantObject => {
|
||||
return {
|
||||
//Default values:
|
||||
created_at: new Date().getTime(),
|
||||
created_by: platform?.currentUser.id || "",
|
||||
company_id: platform?.workspace.company_id || "",
|
||||
workspace_id: platform?.workspace.workspace_id || "",
|
||||
id: platform?.currentUser.id || "",
|
||||
type: "user",
|
||||
|
||||
...participant,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,381 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { Channel } from "../../../src/services/channels/entities/channel";
|
||||
import { ChannelMemberNotificationLevel } from "../../../src/services/channels/types";
|
||||
import { User } from "../../../src/utils/types";
|
||||
import {
|
||||
ChannelMemberUtils,
|
||||
ChannelUtils,
|
||||
get as getChannelUtils,
|
||||
getMemberUtils,
|
||||
} from "../channels/utils";
|
||||
import { MessageNotification } from "../../../src/services/messages/types";
|
||||
import {
|
||||
IncomingPubsubMessage,
|
||||
MessageQueueServiceAPI,
|
||||
} from "../../../src/core/platform/services/message-queue/api";
|
||||
import { ChannelMember } from "../../../src/services/channels/entities";
|
||||
import { MentionNotification } from "../../../src/services/notifications/types";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The notification for user mentions", () => {
|
||||
let platform: TestPlatform;
|
||||
let channelUtils: ChannelUtils;
|
||||
let channelMemberUtils: ChannelMemberUtils;
|
||||
let pubsubService: MessageQueueServiceAPI;
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
let pubsubHandler: (message: IncomingPubsubMessage<MentionNotification>) => void = _ => {};
|
||||
|
||||
beforeAll(async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"websocket",
|
||||
"channels",
|
||||
"auth",
|
||||
"search",
|
||||
"applications",
|
||||
"files",
|
||||
"push",
|
||||
"notifications",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
channelUtils = getChannelUtils(platform);
|
||||
channelMemberUtils = getMemberUtils(platform);
|
||||
pubsubService = platform.platform.getProvider<MessageQueueServiceAPI>("message-queue");
|
||||
pubsubService.subscribe<MentionNotification>("notification:mentions", message => {
|
||||
pubsubHandler(message);
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
});
|
||||
|
||||
async function createChannel(): Promise<Channel> {
|
||||
const channel = channelUtils.getChannel(platform.currentUser.id);
|
||||
const creationResult = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext(),
|
||||
);
|
||||
|
||||
return creationResult.entity;
|
||||
}
|
||||
|
||||
async function joinChannel(
|
||||
userId: string,
|
||||
channel: Channel,
|
||||
notificationLevel?: ChannelMemberNotificationLevel,
|
||||
): Promise<ChannelMember> {
|
||||
const user: User = { id: userId };
|
||||
const member = channelMemberUtils.getMember(channel, user);
|
||||
|
||||
if (notificationLevel) member.notification_level = notificationLevel;
|
||||
|
||||
const memberCreationResult = await gr.services.channels.members.save(
|
||||
member,
|
||||
channelUtils.getChannelContext(channel, user),
|
||||
);
|
||||
return memberCreationResult.entity;
|
||||
}
|
||||
|
||||
async function updateNotificationLevel(
|
||||
channel: Channel,
|
||||
member: ChannelMember,
|
||||
level: ChannelMemberNotificationLevel,
|
||||
): Promise<void> {
|
||||
member.notification_level = level;
|
||||
await gr.services.channels.members.save(
|
||||
member,
|
||||
channelUtils.getChannelContext(channel, { id: member.user_id }),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
function pushMessage(message: MessageNotification): Promise<void> {
|
||||
return pubsubService.publish<MessageNotification>("message:created", {
|
||||
data: message,
|
||||
});
|
||||
}
|
||||
|
||||
it("should mention all users when preferences are MENTION", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const unknownUser = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(
|
||||
platform.currentUser.id,
|
||||
channel,
|
||||
ChannelMemberNotificationLevel.MENTIONS,
|
||||
);
|
||||
const member2 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.MENTIONS);
|
||||
const member3 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.MENTIONS);
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [member.user_id, member2.user_id, unknownUser, member3.user_id],
|
||||
},
|
||||
title: "test",
|
||||
text: "should mention all users when preferences are MENTION ones",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id); //The sender is not in the notified users
|
||||
expect(message.data.mentions.users).toContain(member2.user_id);
|
||||
expect(message.data.mentions.users).toContain(member3.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(unknownUser);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should mention all users when preferences are default ones (ALL)", async done => {
|
||||
const messageId = uuidv1();
|
||||
const unknownUser = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(platform.currentUser.id, channel);
|
||||
const member2 = await joinChannel(uuidv1(), channel);
|
||||
const member3 = await joinChannel(uuidv1(), channel);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); //Wait for the channel members to be created on all services
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: messageId, //Only thread initial messages generate notifications
|
||||
workspace_id: channel.workspace_id,
|
||||
title: "test",
|
||||
text: "should mention all users when preferences are default ones (ALL)",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id); //The sender is not in the notified users
|
||||
expect(message.data.mentions.users).toContain(member2.user_id);
|
||||
expect(message.data.mentions.users).toContain(member3.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(unknownUser);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not mention users with preferences ALL for replies of threads there are not member of", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(platform.currentUser.id, channel);
|
||||
const member2 = await joinChannel(uuidv1(), channel);
|
||||
const member3 = await joinChannel(uuidv1(), channel);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); //Wait for the channel members to be created on all services
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [member.user_id, member2.user_id],
|
||||
},
|
||||
title: "test",
|
||||
text: "should mention all users when preferences are default ones (ALL)",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id); //The sender is not in the notified users
|
||||
expect(message.data.mentions.users).not.toContain(member3.user_id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should not mention user when notification level is set to NONE", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const unknownUser = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(
|
||||
platform.currentUser.id,
|
||||
channel,
|
||||
ChannelMemberNotificationLevel.MENTIONS,
|
||||
);
|
||||
const member2 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.NONE);
|
||||
const member3 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.MENTIONS);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); //Wait for the channel members to be created on all services
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [member.user_id, member2.user_id, unknownUser, member3.user_id],
|
||||
},
|
||||
title: "test",
|
||||
text: "should not mention user when notification level is set to NONE",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id);
|
||||
expect(message.data.mentions.users).toContain(member3.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(member2.user_id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should mention user when notification level is set to channel mention and notification is for @all", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(
|
||||
platform.currentUser.id,
|
||||
channel,
|
||||
ChannelMemberNotificationLevel.MENTIONS,
|
||||
);
|
||||
const member2 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.MENTIONS);
|
||||
const member3 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.ME);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); //Wait for the channel members to be created on all services
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [],
|
||||
specials: ["all"],
|
||||
},
|
||||
title: "test",
|
||||
text: "should mention user when notification level is set to channel mention and notification is for @all",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id);
|
||||
expect(message.data.mentions.users).toContain(member2.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(member3.user_id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should mention user when notification level is set to channel mention and notification is for @here", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(platform.currentUser.id, channel);
|
||||
const member2 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.MENTIONS);
|
||||
const member3 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.ME);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 500)); //Wait for the channel members to be created on all services
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [],
|
||||
specials: ["here"],
|
||||
},
|
||||
title: "test",
|
||||
text: "should mention user when notification level is set to channel mention and notification is for @here",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
|
||||
//Sender dont get notified
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id);
|
||||
expect(message.data.mentions.users).toContain(member2.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(member3.user_id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should mention user when notification level is set to ME and updated notification later", async done => {
|
||||
const threadId = uuidv1();
|
||||
const messageId = uuidv1();
|
||||
const channel = await createChannel();
|
||||
const member = await joinChannel(
|
||||
platform.currentUser.id,
|
||||
channel,
|
||||
ChannelMemberNotificationLevel.NONE,
|
||||
);
|
||||
const member2 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.NONE);
|
||||
const member3 = await joinChannel(uuidv1(), channel, ChannelMemberNotificationLevel.NONE);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)); //Wait for the channel members to be created
|
||||
|
||||
await updateNotificationLevel(channel, member, ChannelMemberNotificationLevel.MENTIONS);
|
||||
await updateNotificationLevel(channel, member2, ChannelMemberNotificationLevel.ME);
|
||||
await updateNotificationLevel(channel, member3, ChannelMemberNotificationLevel.MENTIONS);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)); //Wait for the channel members to be created
|
||||
|
||||
pushMessage({
|
||||
channel_id: channel.id,
|
||||
company_id: channel.company_id,
|
||||
creation_date: Date.now(),
|
||||
id: messageId,
|
||||
sender: platform.currentUser.id,
|
||||
thread_id: threadId,
|
||||
workspace_id: channel.workspace_id,
|
||||
mentions: {
|
||||
users: [member2.user_id],
|
||||
},
|
||||
title: "test",
|
||||
text: "should mention user when notification level is set to ME and updated notification later",
|
||||
});
|
||||
|
||||
const message = await new Promise<IncomingPubsubMessage<MentionNotification>>(
|
||||
resolve => (pubsubHandler = resolve),
|
||||
);
|
||||
expect(message.data.mentions.users).not.toContain(member.user_id);
|
||||
expect(message.data.mentions.users).not.toContain(member3.user_id);
|
||||
expect(message.data.mentions.users).toContain(member2.user_id);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* To run all tests in local development mode:
|
||||
* cd twake/; docker-compose -f docker-compose.dev.tests.mongo.yml run -e NODE_OPTIONS=--unhandled-rejections=warn -e SEARCH_DRIVER=mongodb -e DB_DRIVER=mongodb -e PUBSUB_TYPE=local node npm run test:e2e
|
||||
*
|
||||
* To run only specific tests:
|
||||
* cd twake/; docker-compose -f docker-compose.dev.tests.mongo.yml run -e NODE_OPTIONS=--unhandled-rejections=warn -e SEARCH_DRIVER=mongodb -e DB_DRIVER=mongodb -e PUBSUB_TYPE=local node npm run test:e2e -- test/e2e/application/app-create-update.spec.ts test/e2e/application/application-events.spec.ts
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const cp = require("child_process");
|
||||
|
||||
let localDevTests = process.argv.slice(2);
|
||||
|
||||
//If we are in the CI tests we will run all the tests
|
||||
if (process.env.CI || localDevTests.length === 0) {
|
||||
localDevTests = false;
|
||||
}
|
||||
|
||||
if (localDevTests) {
|
||||
console.log("Only this tests will be run:", localDevTests);
|
||||
} else {
|
||||
console.log("Will run all the tests");
|
||||
}
|
||||
|
||||
function exec(command, args, debug = false) {
|
||||
return new Promise(done => {
|
||||
const cmd = cp.spawn(command, args, {
|
||||
shell: true,
|
||||
});
|
||||
|
||||
let data = "";
|
||||
let error = "";
|
||||
|
||||
cmd.stdout.on("data", function (data) {
|
||||
if (debug) console.log(data.toString());
|
||||
data += data.toString() + "\n";
|
||||
});
|
||||
|
||||
cmd.stderr.on("data", function (data) {
|
||||
if (debug) console.log(data.toString());
|
||||
error += data.toString() + "\n";
|
||||
});
|
||||
|
||||
cmd.on("exit", function (code) {
|
||||
cmd.kill(9);
|
||||
|
||||
//The delay is to make sure we get all the missing logs
|
||||
setTimeout(() => done({ code, data, error }), code === 0 ? 1 : 5000);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let srcFiles = [];
|
||||
let srcPath = __dirname;
|
||||
function throughDirectory(directory) {
|
||||
fs.readdirSync(directory).forEach(file => {
|
||||
const abs = path.join(directory, file);
|
||||
if (fs.statSync(abs).isDirectory()) return throughDirectory(abs);
|
||||
else return srcFiles.push(abs);
|
||||
});
|
||||
}
|
||||
throughDirectory(srcPath);
|
||||
|
||||
srcFiles = srcFiles.filter(p => p.indexOf(".spec.ts") >= 0 || p.indexOf(".test.ts") >= 0);
|
||||
|
||||
(async () => {
|
||||
let failed = 0;
|
||||
let passed = 0;
|
||||
|
||||
let summary = "";
|
||||
|
||||
for (const path of localDevTests || srcFiles) {
|
||||
const test = path.split("test/e2e/")[1];
|
||||
const testName = `test/e2e/${test}`;
|
||||
const args = `${testName} --forceExit --detectOpenHandles --coverage --coverageDirectory=coverage/e2e/${test} --runInBand --testTimeout=60000 --verbose=true`;
|
||||
|
||||
try {
|
||||
//Show logs in the console if we are doing local dev tests
|
||||
const out = await exec("jest", args.split(" "), !!localDevTests);
|
||||
if (out.code !== 0) {
|
||||
//To get all the logs, we run it again
|
||||
console.log(`FAIL ${testName}`);
|
||||
console.log(out.data);
|
||||
console.log(out.error);
|
||||
if (!localDevTests) await exec("jest", args.split(" "), true);
|
||||
failed++;
|
||||
summary += `FAIL ${testName}\n`;
|
||||
} else {
|
||||
passed++;
|
||||
console.log(`PASS ${testName}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`ERROR ${testName}`);
|
||||
console.log(`-- Error\n ${err}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\nResults: ${passed} passed, ${failed} failed, total ${failed + passed}`);
|
||||
console.log(summary);
|
||||
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"services": [],
|
||||
"webserver": {
|
||||
"port": 3000,
|
||||
"logger": {
|
||||
"level": "warn"
|
||||
}
|
||||
},
|
||||
"websocket": {
|
||||
"path": "/socket",
|
||||
"adapters": {
|
||||
"types": ["redis"],
|
||||
"redis": {
|
||||
"host": "localhost",
|
||||
"port": 6379
|
||||
}
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"jwt": {
|
||||
"secret": "supersecret"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { resolve as pathResolve } from "path";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { FastifyInstance } from "fastify";
|
||||
import { TwakePlatform, TwakePlatformConfiguration } from "../../../src/core/platform/platform";
|
||||
import WebServerAPI from "../../../src/core/platform/services/webserver/provider";
|
||||
import { DatabaseServiceAPI } from "../../../src/core/platform/services/database/api";
|
||||
import AuthServiceAPI from "../../../src/core/platform/services/auth/provider";
|
||||
import { Workspace } from "../../../src/utils/types";
|
||||
import { MessageQueueServiceAPI } from "../../../src/core/platform/services/message-queue/api";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import config from "config";
|
||||
import globalResolver from "../../../src/services/global-resolver";
|
||||
|
||||
type TokenPayload = {
|
||||
sub: string;
|
||||
org?: {
|
||||
[companyId: string]: {
|
||||
role: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
isWorkspaceModerator?: boolean;
|
||||
};
|
||||
|
||||
export interface TestPlatform {
|
||||
currentUser: User;
|
||||
platform: TwakePlatform;
|
||||
workspace: Workspace;
|
||||
app: FastifyInstance;
|
||||
database: DatabaseServiceAPI;
|
||||
messageQueue: MessageQueueServiceAPI;
|
||||
authService: AuthServiceAPI;
|
||||
auth: {
|
||||
getJWTToken(payload?: TokenPayload): Promise<string>;
|
||||
};
|
||||
tearDown(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface TestPlatformConfiguration {
|
||||
services: string[];
|
||||
}
|
||||
|
||||
let testPlatform: TestPlatform = null;
|
||||
|
||||
export async function init(
|
||||
testConfig?: TestPlatformConfiguration,
|
||||
prePlatformStartCallback?: (fastify: FastifyInstance) => void,
|
||||
): Promise<TestPlatform> {
|
||||
if (!testPlatform) {
|
||||
const configuration: TwakePlatformConfiguration = {
|
||||
services: config.get("services"),
|
||||
servicesPath: pathResolve(__dirname, "../../../src/services/"),
|
||||
};
|
||||
const platform = new TwakePlatform(configuration);
|
||||
await platform.init();
|
||||
await globalResolver.doInit(platform);
|
||||
|
||||
const app = platform.getProvider<WebServerAPI>("webserver").getServer();
|
||||
|
||||
if (prePlatformStartCallback) {
|
||||
prePlatformStartCallback(app);
|
||||
}
|
||||
|
||||
await platform.start();
|
||||
|
||||
const database = platform.getProvider<DatabaseServiceAPI>("database");
|
||||
const messageQueue = platform.getProvider<MessageQueueServiceAPI>("message-queue");
|
||||
const auth = platform.getProvider<AuthServiceAPI>("auth");
|
||||
|
||||
testPlatform = {
|
||||
platform,
|
||||
app,
|
||||
messageQueue,
|
||||
database,
|
||||
workspace: { company_id: "", workspace_id: "" },
|
||||
currentUser: { id: "" },
|
||||
authService: auth,
|
||||
auth: {
|
||||
getJWTToken,
|
||||
},
|
||||
tearDown,
|
||||
};
|
||||
}
|
||||
|
||||
testPlatform.app.server.close();
|
||||
|
||||
testPlatform.currentUser = { id: uuidv1() };
|
||||
testPlatform.workspace = {
|
||||
company_id: uuidv1(),
|
||||
workspace_id: uuidv1(),
|
||||
};
|
||||
|
||||
testPlatform.app.server.listen(3000);
|
||||
//await testPlatform.messageQueue.start();
|
||||
|
||||
async function getJWTToken(
|
||||
payload: TokenPayload = { sub: testPlatform.currentUser.id },
|
||||
): Promise<string> {
|
||||
if (!payload.sub) {
|
||||
payload.sub = testPlatform.currentUser.id;
|
||||
}
|
||||
|
||||
if (testPlatform.currentUser.isWorkspaceModerator) {
|
||||
payload.org = {};
|
||||
payload.org[testPlatform.workspace.company_id] = {
|
||||
role: "",
|
||||
};
|
||||
}
|
||||
|
||||
return testPlatform.authService.sign(payload);
|
||||
}
|
||||
|
||||
async function tearDown(): Promise<void> {
|
||||
if (testPlatform) {
|
||||
testPlatform.app.server.close();
|
||||
//await testPlatform.messageQueue.stop();
|
||||
}
|
||||
}
|
||||
|
||||
return testPlatform;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "./setup";
|
||||
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import {
|
||||
createMessage,
|
||||
createParticipant,
|
||||
e2e_createMessage,
|
||||
e2e_createThread,
|
||||
} from "./messages/utils";
|
||||
import { Thread } from "../../src/services/messages/entities/threads";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { WorkspaceExecutionContext } from "../../src/services/channels/types";
|
||||
import { ChannelUtils, get as getChannelUtils } from "./channels/utils";
|
||||
import { ResourceUpdateResponse, User } from "../../src/utils/types";
|
||||
import gr from "../../src/services/global-resolver";
|
||||
|
||||
describe("Statistics implementation", () => {
|
||||
let platform: TestPlatform;
|
||||
// let database: DatabaseServiceAPI;
|
||||
let channelUtils: ChannelUtils;
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: ["database", "statistics", "webserver", "auth"],
|
||||
});
|
||||
|
||||
expect(gr.services.statistics).toBeTruthy();
|
||||
|
||||
ends();
|
||||
channelUtils = getChannelUtils(platform);
|
||||
});
|
||||
|
||||
beforeEach(async ends => {
|
||||
await platform.database.getConnector().drop();
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async done => {
|
||||
await platform.tearDown();
|
||||
done();
|
||||
});
|
||||
|
||||
it("Check statistics counters", async done => {
|
||||
console.log(await gr.services.statistics.get(undefined, "counter-test"));
|
||||
|
||||
expect(await gr.services.statistics.get(undefined, "counter-test")).toEqual(0);
|
||||
|
||||
await gr.services.statistics.increase(platform.workspace.company_id, "counter-test");
|
||||
await gr.services.statistics.increase(platform.workspace.company_id, "counter-test");
|
||||
const secondCompanyId = uuidv1();
|
||||
await gr.services.statistics.increase(secondCompanyId, "counter-test");
|
||||
await gr.services.statistics.increase(secondCompanyId, "counter-test");
|
||||
await gr.services.statistics.increase(platform.workspace.company_id, "counter-test2");
|
||||
|
||||
expect(await gr.services.statistics.get(platform.workspace.company_id, "counter-test")).toEqual(
|
||||
2,
|
||||
);
|
||||
expect(await gr.services.statistics.get(secondCompanyId, "counter-test")).toEqual(2);
|
||||
expect(await gr.services.statistics.get(undefined, "counter-test")).toEqual(4);
|
||||
|
||||
expect(
|
||||
await gr.services.statistics.get(platform.workspace.company_id, "counter-test2"),
|
||||
).toEqual(1);
|
||||
expect(await gr.services.statistics.get(secondCompanyId, "counter-test2")).toEqual(0);
|
||||
expect(await gr.services.statistics.get(undefined, "counter-test2")).toEqual(1);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
function getContext(user?: User): WorkspaceExecutionContext {
|
||||
return {
|
||||
workspace: platform.workspace,
|
||||
user: user || platform.currentUser,
|
||||
};
|
||||
}
|
||||
|
||||
async function sleep(timeout = 0) {
|
||||
return new Promise(r => setTimeout(r, timeout));
|
||||
}
|
||||
|
||||
describe("On user use messages in channel view", () => {
|
||||
it("should create a message and retrieve it in channel view", async () => {
|
||||
const channel = channelUtils.getChannel();
|
||||
await gr.services.channels.channels.save(channel, {}, getContext());
|
||||
const channelId = channel.id;
|
||||
|
||||
//Reset global value because messages could have been created somewhere else
|
||||
const value = await gr.services.statistics.get(undefined, "messages");
|
||||
await gr.services.statistics.increase(undefined, "messages", -value);
|
||||
|
||||
const response = await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channelId,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 1 message" }),
|
||||
);
|
||||
|
||||
await sleep();
|
||||
|
||||
const result: ResourceUpdateResponse<Thread> = deserialize(
|
||||
ResourceUpdateResponse,
|
||||
response.body,
|
||||
);
|
||||
const threadId = result.resource.id;
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 1" }));
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 2" }));
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channelId,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 2 message" }),
|
||||
);
|
||||
|
||||
await e2e_createMessage(platform, threadId, createMessage({ text: "Reply 3" }));
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
createParticipant(
|
||||
{
|
||||
type: "channel",
|
||||
id: channelId,
|
||||
},
|
||||
platform,
|
||||
),
|
||||
],
|
||||
createMessage({ text: "Initial thread 3 message" }),
|
||||
);
|
||||
|
||||
await new Promise(r => setTimeout(r, 5000));
|
||||
|
||||
expect(await gr.services.statistics.get(undefined, "messages")).toEqual(6);
|
||||
expect(await gr.services.statistics.get(platform.workspace.company_id, "messages")).toEqual(
|
||||
6,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import "reflect-metadata";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { Tags } from "../../../src/services/tags/entities/tags";
|
||||
import { deserialize } from "class-transformer";
|
||||
import {
|
||||
ResourceCreateResponse,
|
||||
ResourceGetResponse,
|
||||
ResourceListResponse,
|
||||
} from "../../../src/utils/types";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
|
||||
describe("The Tags feature", () => {
|
||||
const url = "/internal/services/tags/v1";
|
||||
let platform: TestPlatform;
|
||||
let testDbService: TestDbService;
|
||||
const tagIds: string[] = [];
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: ["webserver", "database", "storage", "message-queue", "tags"],
|
||||
});
|
||||
testDbService = await TestDbService.getInstance(platform, true);
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async done => {
|
||||
for (let i = 0; i < tagIds.length; i++) {
|
||||
for (let j = 0; j < tagIds.length; j++) {
|
||||
if (tagIds[j] === tagIds[i] && j !== i) {
|
||||
throw new Error("Tag are not unique");
|
||||
}
|
||||
}
|
||||
}
|
||||
await platform?.tearDown();
|
||||
platform = null;
|
||||
done();
|
||||
});
|
||||
|
||||
describe("Create tag", () => {
|
||||
it("should 201 if creator is a company admin", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "admin",
|
||||
});
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const createTag = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
name: `test${i}`,
|
||||
colour: `#00000${i}`,
|
||||
},
|
||||
});
|
||||
|
||||
const tagResult: ResourceCreateResponse<Tags> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
createTag.body,
|
||||
);
|
||||
expect(createTag.statusCode).toBe(201);
|
||||
expect(tagResult.resource).toBeDefined();
|
||||
expect(tagResult.resource.name).toBe(`test${i}`);
|
||||
expect(tagResult.resource.colour).toBe(`#00000${i}`);
|
||||
expect(tagResult.resource.company_id).toBe(platform.workspace.company_id);
|
||||
expect(tagResult.resource.tag_id).toBe(`test${i}`);
|
||||
|
||||
const getTag = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/${tagResult.resource.tag_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(getTag.statusCode).toBe(200);
|
||||
|
||||
tagIds.push(tagResult.resource.tag_id);
|
||||
}
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 401 if creator is not a company admin", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const createTag = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
name: "testNotAdmin",
|
||||
colour: "#000000",
|
||||
},
|
||||
});
|
||||
expect(createTag.statusCode).toBe(401);
|
||||
|
||||
const tagResult: ResourceCreateResponse<Tags> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
createTag.body,
|
||||
);
|
||||
expect(tagResult.resource).toBe(undefined);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get tag", () => {
|
||||
it("should 200 get a tag", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const getTag = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/${tagIds[0]}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(getTag.statusCode).toBe(200);
|
||||
|
||||
const getResult: ResourceGetResponse<Tags> = deserialize(ResourceGetResponse, getTag.body);
|
||||
expect(getResult.resource).toBeDefined();
|
||||
expect(getResult.resource.name).toBe("test0");
|
||||
expect(getResult.resource.colour).toBe("#000000");
|
||||
expect(getResult.resource.company_id).toBe(platform.workspace.company_id);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 tag does not exist", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const getTag = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/NonExistingTag`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(getTag.statusCode).toBe(200);
|
||||
|
||||
const getResult: ResourceGetResponse<Tags> = deserialize(ResourceGetResponse, getTag.body);
|
||||
expect(getResult.resource).toBe(null);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Update tag", () => {
|
||||
it("Should 204 if user is admin", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "admin",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const updateTag = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
name: "test1",
|
||||
colour: "#000003",
|
||||
},
|
||||
});
|
||||
expect(updateTag.statusCode).toBe(201);
|
||||
|
||||
const tagUpdatedResult: ResourceCreateResponse<Tags> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
updateTag.body,
|
||||
);
|
||||
expect(tagUpdatedResult.resource).toBeDefined();
|
||||
expect(tagUpdatedResult.resource.name).toBe("test1");
|
||||
expect(tagUpdatedResult.resource.colour).toBe("#000003");
|
||||
expect(tagUpdatedResult.resource.company_id).toBe(platform.workspace.company_id);
|
||||
expect(tagUpdatedResult.resource.tag_id).toBe("test1");
|
||||
|
||||
const getUpdatedTag = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/${tagUpdatedResult.resource.tag_id}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(getUpdatedTag.statusCode).toBe(200);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 401 if creator is not a company admin", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const createTag = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/testNotAdmin`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
name: "testNotAdmin",
|
||||
colour: "#000000",
|
||||
},
|
||||
});
|
||||
expect(createTag.statusCode).toBe(401);
|
||||
|
||||
const tagResult: ResourceCreateResponse<Tags> = deserialize(
|
||||
ResourceCreateResponse,
|
||||
createTag.body,
|
||||
);
|
||||
console.log("tagResult2", tagResult, jwtToken);
|
||||
expect(tagResult.resource).toBe(undefined);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("List tags", () => {
|
||||
it("should 200 list a tag", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const listTag = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(listTag.statusCode).toBe(200);
|
||||
|
||||
const tagResult: ResourceListResponse<Tags> = deserialize(ResourceListResponse, listTag.body);
|
||||
expect(tagResult.resources).toBeDefined();
|
||||
for (const tag of tagResult.resources) {
|
||||
expect(tag.name).toBeDefined();
|
||||
expect(tag.colour).toBeDefined();
|
||||
expect(tag.company_id).toBe(platform.workspace.company_id);
|
||||
expect(tag.tag_id).toBeDefined();
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delete tag", () => {
|
||||
it("should 200 if admin delete a tag", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "admin",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const deleteTag = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/${tagIds[0]}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(deleteTag.statusCode).toBe(200);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 if tag does not exist", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "admin",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const deleteTag = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/NonExistingTag`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(deleteTag.statusCode).toBe(200);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 401 if not admin", async done => {
|
||||
const user = await testDbService.createUser([testDbService.defaultWorkspace()], {
|
||||
companyRole: "member",
|
||||
});
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: user.id });
|
||||
const deleteTag = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/tags/${tagIds[0]}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(deleteTag.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
describe("The /users API", () => {
|
||||
const url = "/internal/services/users/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
beforeEach(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"search",
|
||||
"message-queue",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"user",
|
||||
"auth",
|
||||
"applications",
|
||||
"storage",
|
||||
"counter",
|
||||
"workspaces",
|
||||
"console",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
ends();
|
||||
});
|
||||
|
||||
afterEach(async ends => {
|
||||
platform && (await platform.tearDown());
|
||||
platform = null;
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("The GET /users/?search=... route", () => {
|
||||
it("Should find the searched users", async done => {
|
||||
const testDbService = new TestDbService(platform);
|
||||
await testDbService.createCompany(platform.workspace.company_id);
|
||||
const workspacePk = {
|
||||
id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
const workspacePk2 = {
|
||||
id: uuidv1(),
|
||||
company_id: uuidv1(),
|
||||
};
|
||||
await testDbService.createWorkspace(workspacePk);
|
||||
await testDbService.createWorkspace(workspacePk2);
|
||||
await testDbService.createUser([workspacePk], {
|
||||
firstName: "Ha",
|
||||
lastName: "Nguyen",
|
||||
email: "hnguyen@twake.app",
|
||||
});
|
||||
await testDbService.createUser([workspacePk], {
|
||||
firstName: "Harold",
|
||||
lastName: "Georges",
|
||||
email: "hgeorges@twake.app",
|
||||
});
|
||||
await testDbService.createUser([workspacePk], {
|
||||
firstName: "Bob",
|
||||
lastName: "Smith",
|
||||
email: "bob@twake.app",
|
||||
});
|
||||
await testDbService.createUser([workspacePk], {
|
||||
firstName: "Bob",
|
||||
lastName: "Rabiot",
|
||||
email: "rabiot.b@twake.app",
|
||||
});
|
||||
await testDbService.createUser([workspacePk, workspacePk2], {
|
||||
firstName: "Bob",
|
||||
lastName: "Smith-Rabiot",
|
||||
email: "rbs@twake.app",
|
||||
});
|
||||
await testDbService.createUser([workspacePk], {
|
||||
firstName: "Alexïs",
|
||||
lastName: "Goélâns",
|
||||
email: "alexis.goelans@twake.app",
|
||||
});
|
||||
|
||||
//Wait for indexation to happen
|
||||
await new Promise(r => setTimeout(r, 5000));
|
||||
|
||||
let resources = await search("ha");
|
||||
expect(resources.length).toBe(2);
|
||||
|
||||
resources = await search("bob rabiot");
|
||||
|
||||
expect(resources.map(e => e.email).includes("rabiot.b@twake.app")).toBe(true);
|
||||
expect(resources.map(e => e.email).includes("rbs@twake.app")).toBe(true);
|
||||
expect(resources.map(e => e.email).includes("bob@twake.app")).toBe(true);
|
||||
|
||||
resources = await search("alexis");
|
||||
expect(resources[0].email).toBe("alexis.goelans@twake.app");
|
||||
|
||||
resources = await search("ALEXIS");
|
||||
expect(resources[0].email).toBe("alexis.goelans@twake.app");
|
||||
|
||||
resources = await search("AleXis");
|
||||
expect(resources[0].email).toBe("alexis.goelans@twake.app");
|
||||
|
||||
resources = await search("alex");
|
||||
expect(resources[0].email).toBe("alexis.goelans@twake.app");
|
||||
|
||||
resources = await search("àlèXïs");
|
||||
expect(resources[0].email).toBe("alexis.goelans@twake.app");
|
||||
|
||||
resources = await search("rbs");
|
||||
expect(resources[0].email).toBe("rbs@twake.app");
|
||||
|
||||
resources = await search("rbs@twake.app");
|
||||
expect(resources[0].email).toBe("rbs@twake.app");
|
||||
|
||||
resources = await search("bob", workspacePk2.company_id);
|
||||
expect(resources.length).toBe(1);
|
||||
|
||||
resources = await search("rbs@twake.app", workspacePk.company_id);
|
||||
expect(resources[0].email).toBe("rbs@twake.app");
|
||||
|
||||
resources = await search("rbs@twake.app", uuidv1());
|
||||
expect(resources.length).toBe(0);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
async function search(search: string, companyId?: string): Promise<any[]> {
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
search: search,
|
||||
...(companyId ? { search_company_id: companyId } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const json = response.json();
|
||||
expect(json).toMatchObject({ resources: expect.any(Array) });
|
||||
const resources = json.resources;
|
||||
return resources;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,645 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import { CompanyLimitsEnum, UserObject } from "../../../src/services/user/web/types";
|
||||
import { ChannelVisibility } from "../../../src/services/channels/types";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
import { ResourceListResponse, Workspace } from "../../../src/utils/types";
|
||||
import { ChannelSaveOptions } from "../../../src/services/channels/web/types";
|
||||
import { createMessage, e2e_createThread } from "../messages/utils";
|
||||
import { deserialize } from "class-transformer";
|
||||
import { get as getChannelUtils } from "../channels/utils";
|
||||
|
||||
describe("The /users API", () => {
|
||||
const url = "/internal/services/users/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
|
||||
const nonExistentId = uuidv1();
|
||||
|
||||
beforeEach(async ends => {
|
||||
platform = await init();
|
||||
ends();
|
||||
});
|
||||
afterEach(async ends => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
ends();
|
||||
});
|
||||
|
||||
beforeAll(async ends => {
|
||||
const platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"search",
|
||||
"message-queue",
|
||||
"websocket",
|
||||
"applications",
|
||||
"webserver",
|
||||
"user",
|
||||
"auth",
|
||||
"storage",
|
||||
"counter",
|
||||
"console",
|
||||
"workspaces",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
testDbService = await TestDbService.getInstance(platform);
|
||||
await testDbService.createCompany();
|
||||
const workspacePk = { id: uuidv1(), company_id: testDbService.company.id };
|
||||
await testDbService.createWorkspace(workspacePk);
|
||||
await testDbService.createUser([workspacePk], {
|
||||
workspaceRole: "moderator",
|
||||
companyRole: "admin",
|
||||
email: "admin@admin.admin",
|
||||
username: "adminuser",
|
||||
firstName: "admin",
|
||||
});
|
||||
await testDbService.createUser([workspacePk]);
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("The GET /users/:id route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/1`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when user does not exists", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: testDbService.users[0].id });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/${nonExistentId}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({
|
||||
error: "Not Found",
|
||||
message: `User ${nonExistentId} not found`,
|
||||
statusCode: 404,
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 and big response for myself", async done => {
|
||||
const myId = testDbService.users[0].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/${myId}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: myId,
|
||||
provider: expect.any(String),
|
||||
provider_id: expect.any(String),
|
||||
email: expect.any(String),
|
||||
is_verified: expect.any(Boolean),
|
||||
picture: expect.any(String),
|
||||
first_name: expect.any(String),
|
||||
last_name: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
deleted: expect.any(Boolean),
|
||||
status: expect.any(String),
|
||||
last_activity: expect.any(Number),
|
||||
|
||||
//Below is only if this is myself
|
||||
|
||||
preference: expect.objectContaining({
|
||||
locale: expect.any(String),
|
||||
timezone: expect.any(Number),
|
||||
}),
|
||||
});
|
||||
|
||||
expect(resource["companies"]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
role: expect.stringMatching(/owner|admin|member|guest/),
|
||||
status: expect.stringMatching(/active|deactivated|invited/),
|
||||
company: {
|
||||
id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 and short response for another user", async done => {
|
||||
const myId = testDbService.users[0].id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/${anotherUserId}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: anotherUserId,
|
||||
provider: expect.any(String),
|
||||
provider_id: expect.any(String),
|
||||
email: expect.any(String),
|
||||
is_verified: expect.any(Boolean),
|
||||
picture: expect.any(String),
|
||||
first_name: expect.any(String),
|
||||
last_name: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
deleted: expect.any(Boolean),
|
||||
status: expect.any(String),
|
||||
last_activity: expect.any(Number),
|
||||
});
|
||||
|
||||
expect(resource).not.toMatchObject({
|
||||
locale: expect.anything(),
|
||||
timezone: expect.anything(),
|
||||
companies: expect.anything(),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /users route", () => {
|
||||
it("should 401 when user is not authenticated", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 with array of users", async done => {
|
||||
const myId = testDbService.users[0].id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
query: {
|
||||
user_ids: `${myId},${anotherUserId}`,
|
||||
company_ids: "fd96c8a8-ae77-11eb-a1a1-0242ac120005",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const json = response.json();
|
||||
expect(json).toMatchObject({ resources: expect.any(Array) });
|
||||
const resources = json.resources;
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /users/:user_id/companies route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/1/companies`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when user does not exists", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: testDbService.users[0].id });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/${nonExistentId}/companies`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({
|
||||
error: "Not Found",
|
||||
message: `User ${nonExistentId} not found`,
|
||||
statusCode: 404,
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 and on correct request", async done => {
|
||||
const myId = testDbService.users[0].id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/users/${anotherUserId}/companies`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
expect(resources.length).toBeGreaterThan(0);
|
||||
|
||||
for (const resource of resources) {
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
role: expect.stringMatching(/owner|admin|member|guest/),
|
||||
status: expect.stringMatching(/active|deactivated|invited/),
|
||||
});
|
||||
|
||||
if (resource.plan) {
|
||||
expect(resource.plan).toMatchObject({
|
||||
name: expect.any(String),
|
||||
limits: expect.objectContaining({
|
||||
[CompanyLimitsEnum.CHAT_MESSAGE_HISTORY_LIMIT]: expect.any(Number || undefined),
|
||||
[CompanyLimitsEnum.COMPANY_MEMBERS_LIMIT]: expect.any(Number || undefined),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (resources.stats) {
|
||||
expect(resource.plan).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
total_members: expect.any(Number),
|
||||
total_guests: expect.any(Number),
|
||||
});
|
||||
}
|
||||
}
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /companies/:company_id route", () => {
|
||||
it("should 404 when company does not exists", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/11111111-1111-1111-1111-111111111111`,
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when company exists", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const json = response.json();
|
||||
|
||||
expect(json.resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
});
|
||||
|
||||
if (json.resource.plan) {
|
||||
expect(json.resource.plan).toMatchObject({
|
||||
name: expect.any(String),
|
||||
limits: expect.objectContaining({
|
||||
[CompanyLimitsEnum.CHAT_MESSAGE_HISTORY_LIMIT]: expect.any(Number || undefined),
|
||||
[CompanyLimitsEnum.COMPANY_MEMBERS_LIMIT]: expect.any(Number || undefined),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
expect(json.resource.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
total_members: expect.any(Number),
|
||||
total_guests: expect.any(Number),
|
||||
total_messages: expect.any(Number),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("User's device management", () => {
|
||||
const deviceToken = "testDeviceToken";
|
||||
|
||||
describe("Register device (POST)", () => {
|
||||
it("should 400 when type is not FCM", async done => {
|
||||
const myId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/devices`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
type: "another",
|
||||
value: "value",
|
||||
version: "version",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resp = response.json();
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(resp).toMatchObject({
|
||||
statusCode: 400,
|
||||
error: "Bad Request",
|
||||
message: "Type should be FCM only",
|
||||
});
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const firstId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: firstId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/devices`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
type: "FCM",
|
||||
value: deviceToken,
|
||||
version: "1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resp = response.json();
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(resp.resource).toMatchObject({
|
||||
type: "FCM",
|
||||
value: deviceToken,
|
||||
version: "1",
|
||||
});
|
||||
|
||||
const user = await testDbService.getUserFromDb({ id: firstId });
|
||||
expect(user.devices).toMatchObject([deviceToken]);
|
||||
const device = await testDbService.getDeviceFromDb(deviceToken);
|
||||
expect(device).toMatchObject({
|
||||
id: deviceToken,
|
||||
user_id: firstId,
|
||||
type: "FCM",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when register token to another person", async done => {
|
||||
const firstId = testDbService.users[0].id;
|
||||
const secondId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: secondId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/devices`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
payload: {
|
||||
resource: {
|
||||
type: "FCM",
|
||||
value: deviceToken,
|
||||
version: "1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resp = response.json();
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(resp.resource).toMatchObject({
|
||||
type: "FCM",
|
||||
value: deviceToken,
|
||||
version: "1",
|
||||
});
|
||||
|
||||
// second user should have now this token
|
||||
let user = await testDbService.getUserFromDb({ id: secondId });
|
||||
expect(user.devices).toMatchObject([deviceToken]);
|
||||
const device = await testDbService.getDeviceFromDb(deviceToken);
|
||||
expect(device).toMatchObject({
|
||||
id: deviceToken,
|
||||
user_id: secondId,
|
||||
type: "FCM",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
// and first — not
|
||||
|
||||
user = await testDbService.getUserFromDb({ id: firstId });
|
||||
expect(user.devices).toMatchObject([]);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
describe("List registered devices (GET)", () => {
|
||||
it("should 200 when request devices", async done => {
|
||||
const myId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/devices`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const resp = response.json();
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(resp).toMatchObject({
|
||||
resources: [
|
||||
{
|
||||
type: "FCM",
|
||||
value: "testDeviceToken",
|
||||
version: "1",
|
||||
},
|
||||
],
|
||||
});
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("De-register device (DELETE)", () => {
|
||||
it("should 200 when device not found for the user", async done => {
|
||||
const myId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/devices/somethingRandom`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
const user = await testDbService.getUserFromDb({ id: myId });
|
||||
expect(user.devices).toMatchObject([deviceToken]);
|
||||
const device = await testDbService.getDeviceFromDb(deviceToken);
|
||||
expect(device).toMatchObject({
|
||||
id: deviceToken,
|
||||
user_id: myId,
|
||||
type: "FCM",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when device found and device should be removed", async done => {
|
||||
const myId = testDbService.users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/devices/${deviceToken}`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
const user = await testDbService.getUserFromDb({ id: myId });
|
||||
expect(user.devices).toMatchObject([]);
|
||||
const device = await testDbService.getDeviceFromDb(deviceToken);
|
||||
expect(device).toBeFalsy();
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Recent contacts", () => {
|
||||
it("should return list of recent contacts of user", async done => {
|
||||
// api = new Api(platform);
|
||||
const channelUtils = getChannelUtils(platform);
|
||||
|
||||
await testDbService.createDefault(platform);
|
||||
|
||||
const channels = [];
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
// const channel = channelUtils.getChannel();
|
||||
const directChannelIn = channelUtils.getDirectChannel();
|
||||
|
||||
const nextUser = await testDbService.createUser(
|
||||
[{ id: platform.workspace.workspace_id, company_id: platform.workspace.company_id }],
|
||||
{ firstName: "FirstName" + i, lastName: "LastName" + i },
|
||||
);
|
||||
|
||||
const members = [platform.currentUser.id, nextUser.id];
|
||||
const directWorkspace: Workspace = {
|
||||
company_id: platform.workspace.company_id,
|
||||
workspace_id: ChannelVisibility.DIRECT,
|
||||
};
|
||||
await Promise.all([
|
||||
// gr.services.channels.channels.save(channel, {}, getContext()),
|
||||
gr.services.channels.channels.save<ChannelSaveOptions>(
|
||||
directChannelIn,
|
||||
{
|
||||
members,
|
||||
},
|
||||
{
|
||||
...{
|
||||
workspace: platform.workspace,
|
||||
user: platform.currentUser,
|
||||
},
|
||||
...{ workspace: directWorkspace },
|
||||
},
|
||||
),
|
||||
]);
|
||||
channels.push(directChannelIn);
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await e2e_createThread(
|
||||
platform,
|
||||
[
|
||||
{
|
||||
company_id: platform.workspace.company_id,
|
||||
created_at: 0,
|
||||
created_by: "",
|
||||
id: channels[2].id,
|
||||
type: "channel",
|
||||
workspace_id: "direct",
|
||||
},
|
||||
],
|
||||
createMessage({ text: "Some message" }),
|
||||
);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken();
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${platform.workspace.company_id}/users/recent`,
|
||||
headers: {
|
||||
authorization: `Bearer ${jwtToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const result: ResourceListResponse<UserObject> = deserialize(
|
||||
ResourceListResponse,
|
||||
response.body,
|
||||
);
|
||||
|
||||
expect(result.resources.length).toEqual(5);
|
||||
expect(result.resources[0].first_name).toEqual("FirstName2");
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { TestPlatform } from "./setup";
|
||||
import { InjectPayload, Response } from "light-my-request";
|
||||
import { logger as log } from "../../src/core/platform/framework";
|
||||
|
||||
declare global {
|
||||
interface ApiResponse extends Response {
|
||||
resources: any[];
|
||||
resource: any;
|
||||
}
|
||||
}
|
||||
|
||||
export class Api {
|
||||
constructor(protected platform: TestPlatform) {}
|
||||
|
||||
private async convertResponse(response: Promise<Response>): Promise<ApiResponse> {
|
||||
const apiResponse = (await response) as ApiResponse;
|
||||
if (apiResponse.statusCode !== 204) {
|
||||
const json = apiResponse.json();
|
||||
apiResponse.resources = json.resources;
|
||||
apiResponse.resource = json.resource;
|
||||
}
|
||||
return apiResponse;
|
||||
}
|
||||
|
||||
private getJwtToken(userId: string) {
|
||||
return this.platform.auth.getJWTToken({ sub: userId });
|
||||
}
|
||||
|
||||
async request(
|
||||
method: "GET" | "POST",
|
||||
url: string,
|
||||
payload: InjectPayload,
|
||||
userId: string,
|
||||
headers: any,
|
||||
): Promise<ApiResponse> {
|
||||
if (!userId) userId = this.platform.currentUser.id;
|
||||
|
||||
let totalHeaders = { authorization: `Bearer ${await this.getJwtToken(userId)}` };
|
||||
|
||||
if (headers) {
|
||||
totalHeaders = { ...totalHeaders, ...headers };
|
||||
}
|
||||
|
||||
return this.convertResponse(
|
||||
this.platform.app
|
||||
.inject({
|
||||
method,
|
||||
url,
|
||||
headers: totalHeaders,
|
||||
payload,
|
||||
})
|
||||
.then(a => {
|
||||
if (a.statusCode !== 204) {
|
||||
log.debug(a.json(), `${method} ${url}`);
|
||||
}
|
||||
return a;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public async get(url: string, userId?: string, headers?: any): Promise<ApiResponse> {
|
||||
return this.request("GET", url, undefined, userId, headers);
|
||||
}
|
||||
|
||||
public async post(
|
||||
url: string,
|
||||
payload: InjectPayload,
|
||||
userId?: string,
|
||||
headers?: any,
|
||||
): Promise<ApiResponse> {
|
||||
return this.request("POST", url, payload, userId, headers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { TestPlatform } from "./setup";
|
||||
import User from "./../../src/services/user/entities/user";
|
||||
import Company, {
|
||||
getInstance as getCompanyInstance,
|
||||
} from "./../../src/services/user/entities/company";
|
||||
import Workspace, {
|
||||
getInstance as getWorkspaceInstance,
|
||||
WorkspacePrimaryKey,
|
||||
} from "./../../src/services/workspaces/entities/workspace";
|
||||
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import CompanyUser from "../../src/services/user/entities/company_user";
|
||||
import { DatabaseServiceAPI } from "../../src/core/platform/services/database/api";
|
||||
import Repository from "../../src/core/platform/services/database/services/orm/repository/repository";
|
||||
import Device from "../../src/services/user/entities/device";
|
||||
|
||||
import gr from "../../src/services/global-resolver";
|
||||
import { Channel } from "../../src/services/channels/entities";
|
||||
import { get as getChannelUtils } from "./channels/utils";
|
||||
|
||||
export type uuid = string;
|
||||
|
||||
export class TestDbService {
|
||||
private deviceRepository: Repository<Device>;
|
||||
|
||||
public static async getInstance(
|
||||
testPlatform: TestPlatform,
|
||||
createDefault = false,
|
||||
): Promise<TestDbService> {
|
||||
const instance = new this(testPlatform);
|
||||
await instance.init();
|
||||
if (createDefault) {
|
||||
await instance.createDefault(testPlatform);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public company: Company;
|
||||
public users: User[];
|
||||
private workspacesMap: Map<string, { workspace: Workspace; users: User[] }>;
|
||||
private userService;
|
||||
|
||||
rand = () => Math.floor(Math.random() * 100000);
|
||||
private database: DatabaseServiceAPI;
|
||||
|
||||
private companyUserRepository: Repository<CompanyUser>;
|
||||
private userRepository: Repository<User>;
|
||||
|
||||
constructor(protected testPlatform: TestPlatform) {
|
||||
this.database = this.testPlatform.platform.getProvider<DatabaseServiceAPI>("database");
|
||||
this.users = [];
|
||||
this.workspacesMap = new Map<string, { workspace: Workspace; users: User[] }>();
|
||||
this.workspacesMap.set("direct", {
|
||||
workspace: { id: "direct" } as Workspace,
|
||||
users: [],
|
||||
});
|
||||
}
|
||||
|
||||
private async init() {
|
||||
this.userRepository = await this.database.getRepository<User>("user", User);
|
||||
this.companyUserRepository = await this.database.getRepository<CompanyUser>(
|
||||
"group_user",
|
||||
CompanyUser,
|
||||
);
|
||||
this.deviceRepository = await this.database.getRepository<Device>("device", Device);
|
||||
}
|
||||
|
||||
public get workspaces() {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
return [...this.workspacesMap.values()].filter(w => w.workspace.id !== "direct");
|
||||
}
|
||||
|
||||
async createCompany(id?: uuid, name?: string): Promise<Company> {
|
||||
if (!name) {
|
||||
name = `TwakeAutotests-test-company-${this.rand()}`;
|
||||
}
|
||||
this.company = await gr.services.companies.createCompany(
|
||||
getCompanyInstance({
|
||||
id: id || uuidv1(),
|
||||
name: name,
|
||||
displayName: name,
|
||||
identity_provider_id: id,
|
||||
}),
|
||||
);
|
||||
return this.company;
|
||||
}
|
||||
|
||||
async createWorkspace(
|
||||
workspacePk: WorkspacePrimaryKey,
|
||||
name = `TwakeAutotests-test-workspace-${this.rand()}`,
|
||||
): Promise<Workspace> {
|
||||
if (!workspacePk.company_id) throw new Error("company_id is not defined for workspace");
|
||||
|
||||
const workspace = await gr.services.workspaces.create(
|
||||
getWorkspaceInstance({
|
||||
id: workspacePk.id,
|
||||
name: name,
|
||||
logo: "workspace_logo",
|
||||
company_id: workspacePk.company_id,
|
||||
}),
|
||||
{ user: { id: "", server_request: true } },
|
||||
);
|
||||
|
||||
const createdWorkspace = await gr.services.workspaces.get({
|
||||
id: workspacePk.id,
|
||||
company_id: workspacePk.company_id,
|
||||
});
|
||||
|
||||
if (!createdWorkspace) {
|
||||
throw new Error("workspace wasn't created");
|
||||
}
|
||||
|
||||
const createdWorkspaceEntity = workspace.entity;
|
||||
this.workspacesMap.set(createdWorkspaceEntity.id, {
|
||||
workspace: createdWorkspaceEntity,
|
||||
users: [],
|
||||
});
|
||||
return createdWorkspaceEntity;
|
||||
}
|
||||
|
||||
async createUser(
|
||||
workspacesPk?: Array<WorkspacePrimaryKey>,
|
||||
options: {
|
||||
companyRole?: "member" | "admin" | "guest";
|
||||
workspaceRole?: "member" | "moderator";
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
cache?: User["cache"];
|
||||
} = {},
|
||||
id: string = uuidv1(),
|
||||
): Promise<User> {
|
||||
const user = new User();
|
||||
const random = this.rand();
|
||||
user.id = id;
|
||||
user.username_canonical = options.username || `test${random}`;
|
||||
user.first_name = options.firstName || `test${random}_first_name`;
|
||||
user.last_name = options.lastName || `test${random}_last_name`;
|
||||
user.email_canonical = options.email || `test${random}@twake.app`;
|
||||
user.identity_provider_id = user.id;
|
||||
user.cache = options.cache || user.cache || { companies: [] };
|
||||
|
||||
//Fixme this is cheating, we should correctly set the cache in internal mode in the code
|
||||
user.cache.companies = [
|
||||
...(user.cache.companies || []),
|
||||
...workspacesPk.map(w => w.company_id),
|
||||
];
|
||||
if (options.email) {
|
||||
user.email_canonical = options.email;
|
||||
}
|
||||
const createdUser = (await gr.services.users.create(user)).entity;
|
||||
|
||||
if (options.password) {
|
||||
await gr.services.users.setPassword({ id: createdUser.id }, options.password);
|
||||
}
|
||||
|
||||
this.users.push(createdUser);
|
||||
await gr.services.companies.setUserRole(
|
||||
this.company ? this.company.id : workspacesPk[0].company_id,
|
||||
createdUser.id,
|
||||
options.companyRole ? options.companyRole : "member",
|
||||
);
|
||||
|
||||
if (workspacesPk && workspacesPk.length) {
|
||||
for (const workspacePk of workspacesPk) {
|
||||
await gr.services.workspaces.addUser(
|
||||
workspacePk,
|
||||
{ id: createdUser.id },
|
||||
options.workspaceRole ? options.workspaceRole : "member",
|
||||
);
|
||||
const wsContainer = this.workspacesMap.get(workspacePk.id);
|
||||
wsContainer.users.push(createdUser);
|
||||
}
|
||||
}
|
||||
|
||||
return createdUser;
|
||||
}
|
||||
|
||||
async getUserFromDb(user: Partial<Pick<User, "id" | "identity_provider_id">>): Promise<User> {
|
||||
if (user.id) {
|
||||
return gr.services.users.get({ id: user.id });
|
||||
} else if (user.identity_provider_id) {
|
||||
return gr.services.users.getByConsoleId(user.identity_provider_id);
|
||||
} else {
|
||||
throw new Error("getUserFromDb: Id not provided");
|
||||
}
|
||||
}
|
||||
|
||||
async getDeviceFromDb(id: string): Promise<Device> {
|
||||
return this.deviceRepository.findOne({ id });
|
||||
}
|
||||
|
||||
getCompanyFromDb(companyId: uuid) {
|
||||
return gr.services.companies.getCompany({ id: companyId });
|
||||
}
|
||||
|
||||
getCompanyFromDbByCode(code: uuid) {
|
||||
return gr.services.companies.getCompany({ identity_provider_id: code });
|
||||
}
|
||||
|
||||
async getCompanyUsers(companyId: uuid): Promise<User[]> {
|
||||
const allUsers = await this.userRepository.find({}).then(a => a.getEntities());
|
||||
|
||||
const companyUsers: User[] = [];
|
||||
|
||||
for (const user of allUsers) {
|
||||
const userInCompany = await this.companyUserRepository.findOne({
|
||||
user_id: user.id,
|
||||
group_id: companyId,
|
||||
});
|
||||
if (userInCompany) {
|
||||
companyUsers.push(user);
|
||||
}
|
||||
}
|
||||
return companyUsers;
|
||||
}
|
||||
|
||||
getCompanyUser(companyId: uuid, userId: uuid): Promise<CompanyUser> {
|
||||
return gr.services.companies.getCompanyUser({ id: companyId }, { id: userId });
|
||||
}
|
||||
|
||||
getWorkspaceUsersCountFromDb(workspaceId: string) {
|
||||
return gr.services.workspaces.getUsersCount(workspaceId);
|
||||
}
|
||||
|
||||
async getCompanyUsersCountFromDb(companyId: string) {
|
||||
return gr.services.companies.getUsersCount(companyId);
|
||||
}
|
||||
|
||||
async createDefault(
|
||||
platform: TestPlatform = this.testPlatform,
|
||||
isAdmin: boolean = true,
|
||||
): Promise<TestDbService> {
|
||||
await this.createCompany(platform.workspace.company_id);
|
||||
const ws0pk = {
|
||||
id: platform.workspace.workspace_id,
|
||||
company_id: platform.workspace.company_id,
|
||||
};
|
||||
await this.createWorkspace(ws0pk);
|
||||
await this.createUser(
|
||||
[ws0pk],
|
||||
{
|
||||
firstName: "defaultUser",
|
||||
companyRole: isAdmin ? "admin" : "member",
|
||||
workspaceRole: isAdmin ? "moderator" : "member",
|
||||
},
|
||||
platform.currentUser.id,
|
||||
);
|
||||
return this;
|
||||
}
|
||||
|
||||
getRepository = (type, entity) => {
|
||||
return this.database.getRepository<typeof entity>(type, entity);
|
||||
};
|
||||
|
||||
defaultWorkspace() {
|
||||
return this.workspaces[0].workspace;
|
||||
}
|
||||
|
||||
async createChannel(userId): Promise<Channel> {
|
||||
const channelUtils = getChannelUtils(this.testPlatform);
|
||||
const channel = channelUtils.getChannel(userId);
|
||||
const creationResult = await gr.services.channels.channels.save(
|
||||
channel,
|
||||
{},
|
||||
channelUtils.getContext({ id: userId }),
|
||||
);
|
||||
return creationResult.entity;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { afterEach, beforeEach, describe, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import io from "socket.io-client";
|
||||
|
||||
describe("The Websocket authentication", () => {
|
||||
let platform: TestPlatform;
|
||||
let socket: SocketIOClient.Socket;
|
||||
|
||||
beforeEach(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"user",
|
||||
"websocket",
|
||||
"webserver",
|
||||
"applications",
|
||||
"auth",
|
||||
"realtime",
|
||||
"channels" /* FIXME: platform is not started if a business service is not in dependencies */,
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
socket = io.connect("http://localhost:3000", { path: "/socket" });
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterEach(async ends => {
|
||||
platform && (await platform.tearDown());
|
||||
platform = null;
|
||||
socket && socket.close();
|
||||
socket = null;
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("JWT-based Authentication", () => {
|
||||
it("should not be able to connect without a JWT token", done => {
|
||||
socket.connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", {})
|
||||
.on("authenticated", () => {
|
||||
done(new Error("Should not occur"));
|
||||
})
|
||||
.on("unauthorized", (msg: any) => {
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should not be able to connect with something which is not a JWT token", done => {
|
||||
socket.connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token: "Not a JWT token" })
|
||||
.on("authenticated", () => {
|
||||
done(new Error("Should not occur"));
|
||||
})
|
||||
.on("unauthorized", (msg: any) => {
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should be able to connect with a JWT token", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
|
||||
socket.connect();
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
done();
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import io from "socket.io-client";
|
||||
|
||||
describe("The Realtime API", () => {
|
||||
let platform: TestPlatform;
|
||||
let socket: SocketIOClient.Socket;
|
||||
|
||||
beforeEach(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"webserver",
|
||||
"database",
|
||||
"search",
|
||||
"storage",
|
||||
"message-queue",
|
||||
"applications",
|
||||
"user",
|
||||
"auth",
|
||||
"websocket",
|
||||
"realtime",
|
||||
"channels" /* FIXME: platform is not started if a business service is not in dependencies */,
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
socket = io.connect("http://localhost:3000", { path: "/socket" });
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterEach(async ends => {
|
||||
await platform.tearDown();
|
||||
platform = null;
|
||||
socket && socket.close();
|
||||
socket = null;
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("Joining rooms", () => {
|
||||
it("should fail when token is not defined", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const name = "/ping";
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", { name });
|
||||
socket.on("realtime:join:error", (event: any) => {
|
||||
expect(event.name).toEqual(name);
|
||||
done();
|
||||
});
|
||||
socket.on("realtime:join:success", () => done(new Error("Should not occur")));
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should fail when token is not valid", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const name = "/ping";
|
||||
const roomToken = "invalid token";
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", { name, token: roomToken });
|
||||
socket.on("realtime:join:error", (event: any) => {
|
||||
expect(event.name).toEqual(name);
|
||||
done();
|
||||
});
|
||||
socket.on("realtime:join:success", () => done(new Error("Should not occur")));
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should receive a realtime:join:success when token is valid and room has been joined", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const name = "test";
|
||||
const roomToken = "twake";
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", { name, token: roomToken });
|
||||
socket.on("realtime:join:error", () => done(new Error("Should not occur")));
|
||||
socket.on("realtime:join:success", (event: any) => {
|
||||
expect(event.name).toEqual(name);
|
||||
done();
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Leaving rooms", () => {
|
||||
it("should not fail when room has not been joined first", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const name = "roomtest";
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:leave", { name });
|
||||
socket.on("realtime:leave:error", () => done(new Error("should not fail")));
|
||||
socket.on("realtime:leave:success", (event: any) => {
|
||||
expect(event.name).toEqual(name);
|
||||
done();
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should send success when room has been joined first", async done => {
|
||||
const token = await platform.auth.getJWTToken();
|
||||
const roomToken = "twake";
|
||||
const name = "roomtest";
|
||||
|
||||
socket.on("connect", () => {
|
||||
socket
|
||||
.emit("authenticate", { token })
|
||||
.on("authenticated", () => {
|
||||
socket.emit("realtime:join", { name, token: roomToken });
|
||||
socket.emit("realtime:leave", { name });
|
||||
socket.on("realtime:leave:error", () => done(new Error("should not fail")));
|
||||
socket.on("realtime:leave:success", (event: any) => {
|
||||
expect(event.name).toEqual(name);
|
||||
done();
|
||||
});
|
||||
})
|
||||
.on("unauthorized", () => {
|
||||
done(new Error("Should not occur"));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
import { afterAll, beforeAll, describe, expect, it as _it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
/*
|
||||
THIS TESTS RUNS ONLY FOR THE CONSOLE-MODE (CONSOLE TYPE: INTERNAL)
|
||||
*/
|
||||
|
||||
export const it = (name: string, cb: (a: any) => void) => {
|
||||
_it(name, async done => {
|
||||
if (gr.services.console.consoleType === "internal") {
|
||||
cb(done);
|
||||
} else {
|
||||
console.warn(`[skipped]: ${name} (no-console mode only)`);
|
||||
done();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
describe("The /workspace/pending users API", () => {
|
||||
const url = "/internal/services/workspaces/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
|
||||
const nonExistentId = uuidv1();
|
||||
const companyId = uuidv1();
|
||||
|
||||
const firstEmail = "first@test-user.com";
|
||||
const secondEmail = "second@test-user.com";
|
||||
const thirdEmail = "third@test-user.com";
|
||||
const fourthUser = "fourth@test-user.com";
|
||||
const emailForExistedUser = "exist@email.com";
|
||||
|
||||
async function doTheTest() {
|
||||
return Promise.resolve(gr.services.console.consoleType === "remote");
|
||||
}
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"user",
|
||||
"database",
|
||||
"message-queue",
|
||||
"webserver",
|
||||
"search",
|
||||
"workspaces",
|
||||
"applications",
|
||||
"auth",
|
||||
"console",
|
||||
"storage",
|
||||
"counter",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
await platform.database.getConnector().drop();
|
||||
await platform.database.getConnector().init();
|
||||
testDbService = new TestDbService(platform);
|
||||
await testDbService.createCompany(companyId);
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws1pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws2pk = { id: uuidv1(), company_id: companyId };
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
await testDbService.createWorkspace(ws1pk);
|
||||
await testDbService.createWorkspace(ws2pk);
|
||||
await testDbService.createUser([ws0pk], { companyRole: "member", workspaceRole: "moderator" });
|
||||
await testDbService.createUser([ws0pk], { companyRole: "member", workspaceRole: "member" });
|
||||
await testDbService.createUser([ws1pk], {
|
||||
companyRole: "member",
|
||||
workspaceRole: "member",
|
||||
email: emailForExistedUser,
|
||||
});
|
||||
await testDbService.createUser([ws2pk], {
|
||||
companyRole: "guest",
|
||||
workspaceRole: "member",
|
||||
email: fourthUser,
|
||||
});
|
||||
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
await platform.tearDown();
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("Invite users to a workspace by email", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/invite`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/invite`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
invitations: [
|
||||
{
|
||||
email: firstEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when requester is not at least workspace member", async done => {
|
||||
const workspace_id = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspace_id}/users/invite`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
invitations: [
|
||||
{
|
||||
email: firstEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/invite`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
invitations: [
|
||||
{
|
||||
email: firstEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
{
|
||||
email: secondEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
{
|
||||
email: "exist@email.com",
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
|
||||
expect(resources.length).toBe(3);
|
||||
|
||||
for (const item of resources) {
|
||||
expect(item).toMatchObject({
|
||||
email: expect.stringMatching(/first@test-user.com|second@test-user.com|exist@email.com/),
|
||||
status: "ok",
|
||||
});
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should fail in response with already added users", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/invite`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
invitations: [
|
||||
{
|
||||
email: firstEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
{
|
||||
email: thirdEmail,
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
|
||||
expect(resources.length).toBe(2);
|
||||
|
||||
expect(resources[0]).toMatchObject({
|
||||
email: "first@test-user.com",
|
||||
status: "error",
|
||||
});
|
||||
|
||||
expect(resources[1]).toMatchObject({
|
||||
email: "third@test-user.com",
|
||||
status: "ok",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delete a pending user from a workspace", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/pending/${email}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/pending/${email}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when requester is not at least workspace member", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/pending/${email}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should {status:error} when email is absent in pending list", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/pending/non-exist-email`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toMatchObject({
|
||||
status: "error",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/pending/${email}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toMatchObject({
|
||||
status: "success",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Get list of pending users in workspace", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/pending`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/pending`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when requester is not at least workspace member", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/pending`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/pending`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
console.log("resources A: ", resources);
|
||||
expect(resources.length).toBe(2);
|
||||
|
||||
expect(resources[0]).toMatchObject({
|
||||
email: "second@test-user.com",
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
});
|
||||
|
||||
expect(resources[1]).toMatchObject({
|
||||
email: "third@test-user.com",
|
||||
role: "member",
|
||||
company_role: "member",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("existed user should be added instantly", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const email = "first@test-user.com";
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
|
||||
console.log("resources B: ", resources);
|
||||
expect(resources.find((a: any) => a.user.email === emailForExistedUser)).toBeDefined();
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,469 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService, uuid } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
describe("The /workspace users API", () => {
|
||||
const url = "/internal/services/workspaces/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
|
||||
const nonExistentId = uuidv1();
|
||||
let companyId = "";
|
||||
|
||||
const checkUserObject = (resource: any) => {
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
company_id: expect.any(String),
|
||||
workspace_id: expect.any(String),
|
||||
user_id: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
role: expect.stringMatching(/moderator|member/),
|
||||
user: {
|
||||
id: expect.any(String),
|
||||
provider: expect.any(String),
|
||||
provider_id: expect.any(String),
|
||||
email: expect.any(String),
|
||||
is_verified: expect.any(Boolean),
|
||||
picture: expect.any(String),
|
||||
first_name: expect.any(String),
|
||||
last_name: expect.any(String),
|
||||
created_at: expect.any(Number),
|
||||
deleted: expect.any(Boolean),
|
||||
status: expect.any(String),
|
||||
last_activity: expect.any(Number),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"message-queue",
|
||||
"search",
|
||||
"webserver",
|
||||
"user",
|
||||
"workspaces",
|
||||
"applications",
|
||||
"auth",
|
||||
"console",
|
||||
"counter",
|
||||
"storage",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
companyId = platform.workspace.company_id;
|
||||
|
||||
await platform.database.getConnector().init();
|
||||
testDbService = new TestDbService(platform);
|
||||
await testDbService.createCompany(companyId);
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws1pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws2pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws3pk = { id: uuidv1(), company_id: companyId };
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
await testDbService.createWorkspace(ws1pk);
|
||||
await testDbService.createWorkspace(ws2pk);
|
||||
await testDbService.createWorkspace(ws3pk);
|
||||
await testDbService.createUser([ws0pk, ws1pk]);
|
||||
await testDbService.createUser([ws2pk], { companyRole: "admin" });
|
||||
await testDbService.createUser([ws2pk], { workspaceRole: "moderator" });
|
||||
await testDbService.createUser([ws2pk], { workspaceRole: "member" });
|
||||
await testDbService.createUser([ws2pk], { workspaceRole: "member" });
|
||||
await testDbService.createUser([], { companyRole: "member" });
|
||||
await testDbService.createUser([ws3pk], { companyRole: "guest", workspaceRole: "member" });
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
await platform.tearDown();
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("The GET /workspaces/users route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
|
||||
expect(resources.length).toBeGreaterThan(0);
|
||||
|
||||
for (const resource of resources) {
|
||||
checkUserObject(resource);
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /workspaces/users/:user_id route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${userId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
checkUserObject(resource);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The POST /workspaces/users route (add)", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 user is not workspace moderator", async done => {
|
||||
const userId = testDbService.users[0].id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: anotherUserId,
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 400 when requested user not in company", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: nonExistentId,
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 201 when requested already in workspace (ignore)", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: userId,
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(201);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
const anotherUserId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
let workspaceUsersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
|
||||
let companyUsersCount = await testDbService.getCompanyUsersCountFromDb(companyId);
|
||||
|
||||
console.log(testDbService.workspaces[2].users);
|
||||
console.log(workspaceUsersCount);
|
||||
|
||||
expect(workspaceUsersCount).toBe(4);
|
||||
// expect(companyUsersCount).toBe(6);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: anotherUserId,
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const resource = response.json()["resource"];
|
||||
checkUserObject(resource);
|
||||
|
||||
workspaceUsersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
|
||||
companyUsersCount = await testDbService.getCompanyUsersCountFromDb(companyId);
|
||||
expect(workspaceUsersCount).toBe(5);
|
||||
// expect(companyUsersCount).toBe(6);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The POST /workspaces/users/:user_id route (update)", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.users[0].id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 user is not workspace moderator", async done => {
|
||||
const userId = testDbService.users[0].id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${userId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
user_id: anotherUserId,
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when user not found in workspace", async done => {
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
const anotherWorkspaceUserId = testDbService.workspaces[3].users[0].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherWorkspaceUserId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
const anotherUserId = testDbService.workspaces[2].users[2].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
role: "moderator",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const resource = response.json()["resource"];
|
||||
checkUserObject(resource);
|
||||
|
||||
expect(resource["role"]).toBe("moderator");
|
||||
|
||||
const usersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
|
||||
expect(usersCount).toBe(5);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The DELETE /workspaces/users/:user_id route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const anotherUserId = testDbService.users[1].id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${anotherUserId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 user is not workspace moderator", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[3].id;
|
||||
const anotherUserId = testDbService.workspaces[2].users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
console.log(response.body);
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when user not found in workspace", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${nonExistentId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when ok", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id;
|
||||
const anotherUserId = testDbService.workspaces[2].users[2].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
let response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const resources = response.json()["resources"];
|
||||
expect(resources.find((a: { user_id: uuid }) => a.user_id === anotherUserId)).toBeUndefined();
|
||||
|
||||
const usersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
|
||||
expect(usersCount).toBe(4);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,521 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
import AuthService from "../../../src/core/platform/services/auth/provider";
|
||||
import { InviteTokenObject } from "../../../src/services/workspaces/web/types";
|
||||
import gr from "../../../src/services/global-resolver";
|
||||
|
||||
describe("The /workspaces API (invite tokens)", () => {
|
||||
const url = "/internal/services/workspaces/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
let authServiceApi: AuthService;
|
||||
|
||||
let companyId = uuidv1();
|
||||
|
||||
const startup = async () => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"message-queue",
|
||||
"webserver",
|
||||
"user",
|
||||
"search",
|
||||
"workspaces",
|
||||
"auth",
|
||||
"console",
|
||||
"counter",
|
||||
"storage",
|
||||
"applications",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
companyId = platform.workspace.company_id;
|
||||
|
||||
await platform.platform.getProvider<AuthService>("auth");
|
||||
testDbService = new TestDbService(platform);
|
||||
await resetDatabase();
|
||||
};
|
||||
|
||||
const shutdown = async () => {
|
||||
await platform.tearDown();
|
||||
};
|
||||
|
||||
const resetDatabase = async () => {
|
||||
// await platform.database.getConnector().init();
|
||||
await platform.database.getConnector().drop();
|
||||
await testDbService.createCompany(companyId, "TestJoinCompany");
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws1pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws2pk = { id: uuidv1(), company_id: companyId };
|
||||
await testDbService.createWorkspace(ws0pk, "FirstWorkspace");
|
||||
await testDbService.createWorkspace(ws1pk, "SecondWorkspace");
|
||||
await testDbService.createWorkspace(ws2pk, "ThirdWorkspace");
|
||||
await testDbService.createUser([ws0pk, ws1pk]);
|
||||
await testDbService.createUser([ws2pk], { companyRole: "admin" });
|
||||
await testDbService.createUser([ws2pk], { companyRole: undefined, workspaceRole: "moderator" });
|
||||
await testDbService.createUser([], { companyRole: "guest" });
|
||||
};
|
||||
|
||||
const decodeToken = (token: string): InviteTokenObject => {
|
||||
return gr.services.workspaces.decodeInviteToken(token);
|
||||
};
|
||||
|
||||
describe("The GET /tokens/ route", () => {
|
||||
beforeAll(startup);
|
||||
afterAll(shutdown);
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user is not a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userIdFromAnotherWorkspace = platform.currentUser.id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when token doesn't exists yet", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
await gr.services.workspaces.createInviteToken(companyId, workspaceId, userId);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(response.json()).toMatchObject({
|
||||
resources: [
|
||||
{
|
||||
token: expect.any(String),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The POST /tokens/ route", () => {
|
||||
beforeAll(startup);
|
||||
afterAll(shutdown);
|
||||
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user is not a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userIdFromAnotherWorkspace = platform.currentUser.id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
channels: ["test"],
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
const channel = await testDbService.createChannel(userId);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const beforeResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(beforeResponse.statusCode).toBe(404);
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
channels: [channel.id],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
expect(response.json()).toMatchObject({
|
||||
resource: {
|
||||
token: expect.any(String),
|
||||
},
|
||||
});
|
||||
|
||||
const createToken = decodeToken(response.json().resource.token);
|
||||
|
||||
const afterResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(afterResponse.statusCode).toBe(200);
|
||||
|
||||
expect(afterResponse.json()).toMatchObject({
|
||||
resources: [
|
||||
{
|
||||
token: expect.any(String),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const getToken = decodeToken(afterResponse.json().resources[0].token);
|
||||
|
||||
expect(createToken.t).toEqual(getToken.t);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when when recreate token", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
const channel = await testDbService.createChannel(userId);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const beforeResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(beforeResponse.statusCode).toBe(200);
|
||||
|
||||
const beforeResponseResource = beforeResponse.json()["resources"][0];
|
||||
|
||||
expect(beforeResponseResource).toMatchObject({
|
||||
token: expect.any(String),
|
||||
});
|
||||
|
||||
const beforeResponseToken = decodeToken(beforeResponseResource.token).t;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
channels: [channel.id],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const responseResource = response.json()["resource"];
|
||||
|
||||
expect(responseResource).toMatchObject({
|
||||
token: expect.any(String),
|
||||
});
|
||||
|
||||
const responseToken = decodeToken(responseResource.token).t;
|
||||
|
||||
expect(responseToken).not.toEqual(beforeResponseToken);
|
||||
|
||||
const afterResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(afterResponse.statusCode).toBe(200);
|
||||
|
||||
const afterResponseResource = afterResponse.json()["resources"][0];
|
||||
|
||||
expect(afterResponseResource).toMatchObject({
|
||||
token: expect.any(String),
|
||||
});
|
||||
|
||||
const afterResponseToken = decodeToken(afterResponseResource.token).t;
|
||||
|
||||
expect(responseToken).toEqual(afterResponseToken);
|
||||
expect(afterResponseToken).not.toEqual(beforeResponseToken);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The DELETE /tokens/ route", () => {
|
||||
beforeAll(startup);
|
||||
afterAll(shutdown);
|
||||
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens/fake1-${new Date().getTime()}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user is not a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userIdFromAnotherWorkspace = platform.currentUser.id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens/fake2-${new Date().getTime()}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {},
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 204 when user is a workspace member", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
await gr.services.workspaces.createInviteToken(companyId, workspaceId, userId);
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const beforeResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(beforeResponse.statusCode).toBe(200);
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens/${
|
||||
beforeResponse.json().resources[0].token
|
||||
}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
const afterResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(afterResponse.statusCode).toBe(404);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when deleting token that doesn't exists", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/tokens/fake3-${new Date().getTime()}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {},
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Join workspace using token", () => {
|
||||
let workspaceId;
|
||||
let userId;
|
||||
let companyId;
|
||||
let inviteToken;
|
||||
|
||||
beforeAll(async () => {
|
||||
await startup();
|
||||
companyId = testDbService.company.id;
|
||||
workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
userId = testDbService.workspaces[2].users[0].id;
|
||||
inviteToken = await gr.services.workspaces.createInviteToken(companyId, workspaceId, userId);
|
||||
});
|
||||
afterAll(shutdown);
|
||||
|
||||
it("should 404 when when token not found", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/join`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
join: false,
|
||||
token: "SOME FAKE TOKEN",
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is not authorized", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/join`,
|
||||
// headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
join: false,
|
||||
token: inviteToken.token,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
company: {
|
||||
name: "TestJoinCompany",
|
||||
},
|
||||
workspace: {
|
||||
name: "FirstWorkspace",
|
||||
},
|
||||
auth_required: true,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is authorized and not joining", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/join`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
join: false,
|
||||
token: inviteToken.token,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
company: {
|
||||
name: "TestJoinCompany",
|
||||
},
|
||||
workspace: {
|
||||
name: "FirstWorkspace",
|
||||
},
|
||||
auth_required: false,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is authorized and joining", async done => {
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/join`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
join: true,
|
||||
token: inviteToken.token,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
company: {
|
||||
id: companyId,
|
||||
name: "TestJoinCompany",
|
||||
},
|
||||
workspace: {
|
||||
id: workspaceId,
|
||||
name: "FirstWorkspace",
|
||||
},
|
||||
auth_required: false,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,513 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
||||
import { init, TestPlatform } from "../setup";
|
||||
import { TestDbService } from "../utils.prepare.db";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
describe("The /workspaces API", () => {
|
||||
const url = "/internal/services/workspaces/v1";
|
||||
let platform: TestPlatform;
|
||||
|
||||
let testDbService: TestDbService;
|
||||
|
||||
const nonExistentId = uuidv1();
|
||||
let companyId = "";
|
||||
|
||||
beforeAll(async ends => {
|
||||
platform = await init({
|
||||
services: [
|
||||
"database",
|
||||
"message-queue",
|
||||
"webserver",
|
||||
"user",
|
||||
"search",
|
||||
"workspaces",
|
||||
"auth",
|
||||
"console",
|
||||
"counter",
|
||||
"storage",
|
||||
"applications",
|
||||
"statistics",
|
||||
"platform-services",
|
||||
],
|
||||
});
|
||||
|
||||
companyId = platform.workspace.company_id;
|
||||
|
||||
await platform.database.getConnector().init();
|
||||
testDbService = new TestDbService(platform);
|
||||
await testDbService.createCompany(companyId);
|
||||
const ws0pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws1pk = { id: uuidv1(), company_id: companyId };
|
||||
const ws2pk = { id: uuidv1(), company_id: companyId };
|
||||
await testDbService.createWorkspace(ws0pk);
|
||||
await testDbService.createWorkspace(ws1pk);
|
||||
await testDbService.createWorkspace(ws2pk);
|
||||
await testDbService.createUser([ws0pk, ws1pk]);
|
||||
await testDbService.createUser([ws2pk], { companyRole: "admin" });
|
||||
await testDbService.createUser([ws2pk], { companyRole: undefined, workspaceRole: "moderator" });
|
||||
await testDbService.createUser([], { companyRole: "guest" });
|
||||
ends();
|
||||
});
|
||||
|
||||
afterAll(async ends => {
|
||||
await platform.tearDown();
|
||||
ends();
|
||||
});
|
||||
|
||||
describe("The GET /workspaces/ route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${nonExistentId}/workspaces`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when company not found", async done => {
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${nonExistentId}/workspaces`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when company belongs to user", async done => {
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const companyId = testDbService.company.id;
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resources = response.json()["resources"];
|
||||
|
||||
expect(resources.length).toBe(2);
|
||||
|
||||
for (const resource of resources) {
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
company_id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
default: expect.any(Boolean),
|
||||
archived: expect.any(Boolean),
|
||||
role: expect.stringMatching(/moderator|member/),
|
||||
});
|
||||
|
||||
if (resource.stats) {
|
||||
expect(resource.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
total_members: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("The GET /workspaces/:workspace_id route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${nonExistentId}/workspaces/${workspaceId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 404 when workspace not found", async done => {
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${uuidv1()}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(404);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user not belong to workspace and not company_admin", async done => {
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userIdFromAnotherWorkspace = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
expect(response.json()).toEqual({
|
||||
error: "Forbidden",
|
||||
message: `You are not belong to workspace ${workspaceId}`,
|
||||
statusCode: 403,
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is company_admin", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userIdFromAnotherWorkspace = testDbService.workspaces[2].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
company_id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
default: expect.any(Boolean),
|
||||
archived: expect.any(Boolean),
|
||||
});
|
||||
|
||||
if (resource.stats) {
|
||||
expect(resource.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
total_members: 1,
|
||||
});
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when user is belong to workspace", async done => {
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
const userIdFromThisWorkspace = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromThisWorkspace });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
company_id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
default: expect.any(Boolean),
|
||||
archived: expect.any(Boolean),
|
||||
role: expect.stringMatching(/moderator|member/),
|
||||
});
|
||||
|
||||
if (resource.stats) {
|
||||
expect(resource.stats).toMatchObject({
|
||||
created_at: expect.any(Number),
|
||||
total_members: 1,
|
||||
});
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
// create
|
||||
|
||||
describe("The POST /workspaces route (creating workspace)", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user is not (company member or company admin) ", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.users[3].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
name: "Some channel name",
|
||||
logo: "",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 201 when workspace created well", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.users[0].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
name: "Random channel name",
|
||||
logo: "logo",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: expect.any(String),
|
||||
company_id: expect.any(String),
|
||||
name: expect.any(String),
|
||||
logo: expect.any(String),
|
||||
default: expect.any(Boolean),
|
||||
archived: expect.any(Boolean),
|
||||
role: expect.stringMatching(/moderator/),
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
// update
|
||||
|
||||
describe("The POST /workspaces/:workspace_id route (updating workspace)", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
|
||||
payload: { resource: {} },
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when not workspace not found", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: { resource: {} },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when not belong to workspace", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[1].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: { resource: {} },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when not workspace moderator", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[1].workspace.id;
|
||||
const userId = testDbService.workspaces[0].users[0].id;
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: { resource: {} },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when admin of company (full update)", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id; // company owner
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
name: "Another workspace name",
|
||||
logo: "logo",
|
||||
default: false,
|
||||
archived: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: workspaceId,
|
||||
company_id: companyId,
|
||||
name: "Another workspace name",
|
||||
logo: expect.any(String),
|
||||
default: false,
|
||||
archived: false,
|
||||
role: "moderator", //Company admin is a moderator
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 200 when moderator of workspace (partial update)", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[1].id; // workspace admin
|
||||
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
payload: {
|
||||
resource: {
|
||||
name: "My awesome workspace",
|
||||
default: true,
|
||||
logo: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const resource = response.json()["resource"];
|
||||
|
||||
expect(resource).toMatchObject({
|
||||
id: workspaceId,
|
||||
company_id: companyId,
|
||||
name: "My awesome workspace",
|
||||
logo: expect.any(String),
|
||||
default: true,
|
||||
archived: false,
|
||||
role: "moderator",
|
||||
});
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
// delete
|
||||
|
||||
describe("The DELETE /workspaces route", () => {
|
||||
it("should 401 when not authenticated", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
|
||||
});
|
||||
expect(response.statusCode).toBe(401);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 403 when user is not (company member or company admin) ", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const userId = testDbService.users[3].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
const workspaceId = testDbService.workspaces[0].workspace.id;
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
done();
|
||||
});
|
||||
|
||||
it("should 204 when workspace deleted", async done => {
|
||||
const companyId = testDbService.company.id;
|
||||
const workspaceId = testDbService.workspaces[2].workspace.id;
|
||||
const userId = testDbService.workspaces[2].users[0].id;
|
||||
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
|
||||
|
||||
const response = await platform.app.inject({
|
||||
method: "DELETE",
|
||||
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
const checkResponse = await platform.app.inject({
|
||||
method: "GET",
|
||||
url: `${url}/companies/${companyId}/workspaces`,
|
||||
headers: { authorization: `Bearer ${jwtToken}` },
|
||||
});
|
||||
|
||||
const checkResponseJson = checkResponse.json();
|
||||
|
||||
expect(checkResponseJson.resources.find((a: any) => a.id === workspaceId)).toBe(undefined);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
# Sample HTTP Requests
|
||||
|
||||
Files in this folder works with the [REST Client VSCode extension](https://github.com/Huachao/vscode-restclient).
|
||||
@@ -0,0 +1,19 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@badgesURL = {{baseURL}}/internal/services/notifications/v1/badges
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
### List badges with all websockets
|
||||
|
||||
GET {{badgesURL}}/?company_id={{company_id}}&websockets=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
### Create a channel
|
||||
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My channel",
|
||||
"icon": "twake logo",
|
||||
"description": "This channel allow twake's team to chat easily",
|
||||
"channel_group": "twake",
|
||||
"visibility": "public",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Get a single channel
|
||||
|
||||
@getId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Add current user as member to a channel (join channel)
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"user_id": "{{currentUserId}}"
|
||||
}
|
||||
}
|
||||
|
||||
### Mark the channel as read/unread
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/read
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"value": true
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
### List workspace channels with all websockets
|
||||
|
||||
GET {{channelsURL}}/channels?websockets=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### List user channels with all websockets
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Create a channel
|
||||
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My channel",
|
||||
"icon": "twake logo",
|
||||
"description": "This channel allow twake's team to chat easily",
|
||||
"channel_group": "twake",
|
||||
"visibility": "public",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Get a single channel
|
||||
|
||||
@getId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Update a channel
|
||||
@updateId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
POST {{channelsURL}}/channels/{{updateId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My channel",
|
||||
"description": "Hello world",
|
||||
"is_default": false
|
||||
}
|
||||
}
|
||||
|
||||
### Delete a channel
|
||||
|
||||
@deleteId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{deleteId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
|
||||
### Get all channel members
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
|
||||
### Add current user as member to a channel (join channel)
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"user_id": "{{currentUserId}}"
|
||||
}
|
||||
}
|
||||
|
||||
### Get a channel member
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Update current channel member
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"favorite": true,
|
||||
"notification_level": "none",
|
||||
"hello": 1
|
||||
}
|
||||
}
|
||||
|
||||
### Current user quits the channel
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Errors Tests
|
||||
|
||||
### Call without the JWT token should HTTP 401
|
||||
|
||||
GET {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
|
||||
### Get a channel which may not exists
|
||||
|
||||
GET {{channelsURL}}/channels/0b0e1492-f596-46b9-a4fb-c12d71b2696e
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
### Login as user 1
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken1 = {{login.response.body.token}}
|
||||
@userId1 = {{login.response.body.user.id}}
|
||||
|
||||
### Login as user 2
|
||||
|
||||
# @name login2
|
||||
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken2 = {{login2.response.body.token}}
|
||||
@userId2 = {{login2.response.body.user.id}}
|
||||
|
||||
### Login as user 3
|
||||
|
||||
# @name login3
|
||||
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken3 = {{login3.response.body.token}}
|
||||
@userId3 = {{login3.response.body.user.id}}
|
||||
|
||||
### Create a direct channel
|
||||
|
||||
# @name createDirectChannel
|
||||
POST {{directChannelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
{
|
||||
"options": {
|
||||
"members": ["{{userId2}}"]
|
||||
},
|
||||
"resource": {
|
||||
"icon": "hello",
|
||||
"description": "A direct channel",
|
||||
"channel_group": "twake",
|
||||
"is_default": false,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Direct channel details as user 1 should work
|
||||
@directId = {{createDirectChannel.response.body.resource.id}}
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### Direct channel details as user 2 (member) should work
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken2}}
|
||||
|
||||
### Direct channel details as user 3 (not member) should not work
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken3}}
|
||||
|
||||
### Direct channel members
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### List direct channels for user in company
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
GET {{directChannelsURL}}/channels?websockets=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### Update the direct channel description
|
||||
|
||||
POST {{directChannelsURL}}/channels/{{directId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"description": "A new direct channel description"
|
||||
}
|
||||
}
|
||||
|
||||
### Update the direct channel name will do nothing since the name is useless
|
||||
POST {{directChannelsURL}}/channels/{{directId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "A new direct channel name"
|
||||
}
|
||||
}
|
||||
|
||||
### Update the direct channel member settings for current user
|
||||
|
||||
POST {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"favorite": true,
|
||||
"notification_level": "all"
|
||||
}
|
||||
}
|
||||
|
||||
### Update another user member settings should fail
|
||||
|
||||
POST {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"favorite": true,
|
||||
"notification_level": "none"
|
||||
}
|
||||
}
|
||||
|
||||
### Get member settings as user1
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### Get member settings as user2
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken2}}
|
||||
|
||||
### Get other member settings should fail
|
||||
|
||||
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### Leave a direct channel of another user should fail
|
||||
|
||||
DELETE {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
|
||||
### Leave a direct channel should not fail
|
||||
|
||||
DELETE {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken1}}
|
||||
@@ -0,0 +1,108 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
### Login as user 1
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authTokenUser1 = {{login.response.body.token}}
|
||||
@currentUserId1 = {{login.response.body.user.id}}
|
||||
|
||||
### Login as user 2
|
||||
|
||||
# @name login2
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authTokenUser2 = {{login2.response.body.token}}
|
||||
@currentUserId2 = {{login2.response.body.user.id}}
|
||||
|
||||
### User 1 creates a private channel
|
||||
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My private channel",
|
||||
"icon": "twake logo",
|
||||
"description": "This channel allow twake's team to chat easily",
|
||||
"channel_group": "twake",
|
||||
"visibility": "private",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Get the private channel
|
||||
|
||||
@getId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### Get all channel members
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
|
||||
### The user 2 tries to join the private channel, this should reject
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"user_id": "{{currentUserId2}}"
|
||||
}
|
||||
}
|
||||
|
||||
### The user 1 adds the user 2 as channel member, this should be OK
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"user_id": "{{currentUserId2}}"
|
||||
}
|
||||
}
|
||||
|
||||
### User 2 lists his channels
|
||||
|
||||
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
### Get all channel members as user 1
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### Get all channel members as user 2
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
### User 1 leaves the channel he created
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId1}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### User 2 leaves the channel: Error since he is the last member, he can not leave
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
@@ -0,0 +1,70 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
### List workspace channels with all websockets
|
||||
|
||||
GET {{channelsURL}}/channels?websockets=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### List user channels with all websockets
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Create a private channel
|
||||
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My private channel",
|
||||
"icon": "twake logo",
|
||||
"description": "A private channel",
|
||||
"channel_group": "twake",
|
||||
"visibility": "private",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Get the private channel
|
||||
|
||||
@getId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Get members of the private channel
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Get current user as member
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### Current user quits the private channel will fail because he is the only one in it
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
@@ -0,0 +1,108 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@baseURL = http://localhost:3000
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
|
||||
|
||||
### Login as user 1
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authTokenUser1 = {{login.response.body.token}}
|
||||
@currentUserId1 = {{login.response.body.user.id}}
|
||||
|
||||
### Login as user 2
|
||||
|
||||
# @name login2
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authTokenUser2 = {{login2.response.body.token}}
|
||||
@currentUserId2 = {{login2.response.body.user.id}}
|
||||
|
||||
### User 1 creates a public channel
|
||||
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "A public channel",
|
||||
"icon": "twake logo",
|
||||
"description": "This channel allow twake's team to chat easily",
|
||||
"channel_group": "twake",
|
||||
"visibility": "public",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### Get the public channel
|
||||
|
||||
@getId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### Get all channel members
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
|
||||
### The user 2 joins the public channel, this should be OK
|
||||
|
||||
POST {{channelsURL}}/channels/{{getId}}/members
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"user_id": "{{currentUserId2}}"
|
||||
}
|
||||
}
|
||||
|
||||
### Get all channel members, there are now 2 members
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### User 1 lists his channels
|
||||
|
||||
GET {{channelsURL}}/channels?mine=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### User 2 lists his channels
|
||||
|
||||
GET {{channelsURL}}/channels?mine=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
### User 2 leaves the channel
|
||||
|
||||
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId2}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
### Get all channel members, there are now 1 member, the initial one
|
||||
|
||||
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser1}}
|
||||
|
||||
### List channels as user 2, current channel appears since it is public
|
||||
|
||||
GET {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
|
||||
### User 2 list his public channels, current channel does not appear since he left it
|
||||
|
||||
GET {{channelsURL}}/channels?mine=true
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authTokenUser2}}
|
||||
@@ -0,0 +1,85 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71a
|
||||
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@tabsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}/channels
|
||||
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
|
||||
### List channel's tab with all websockets
|
||||
GET {{tabsURL}}/{{channelId}}/tabs?websockets=true&limit=5
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
|
||||
### Create a channel
|
||||
# @name createChannel
|
||||
POST {{channelsURL}}/channels
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My channel",
|
||||
"icon": "twake logo",
|
||||
"description": "This channel allow twake's team to chat easily",
|
||||
"channel_group": "twake",
|
||||
"visibility": "public",
|
||||
"is_default": true,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
### Create a tab
|
||||
# @name createTab
|
||||
@channelId = {{createChannel.response.body.resource.id}}
|
||||
|
||||
POST {{tabsURL}}/{{channelId}}/tabs
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
// WARNING : special caracter in tab's name does not work
|
||||
"name": "My tabs name",
|
||||
"configuration": "JSON"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
### Get a single tab
|
||||
@getId = {{createTab.response.body.resource.id}}
|
||||
|
||||
GET {{tabsURL}}/{{channelId}}/tabs/{{getId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
|
||||
### Update a tab
|
||||
@updateId = {{createTab.response.body.resource.id}}
|
||||
|
||||
POST {{tabsURL}}/{{channelId}}/tabs/{{updateId}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "My tab updated",
|
||||
"configuration": "JSON"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
### Delete a tab
|
||||
@deleteId = {{createTab.response.body.resource.id}}
|
||||
|
||||
DELETE {{tabsURL}}/{{channelId}}/tabs/{{deleteId}}
|
||||
Authorization: Bearer {{authToken}}
|
||||
@@ -0,0 +1,18 @@
|
||||
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
|
||||
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
|
||||
@user_id = 508c8c1a-706f-11eb-b6be-0242ac120002
|
||||
|
||||
@baseURL = http://localhost:3000
|
||||
@usersURL = {{baseURL}}/internal/services/users/v1
|
||||
|
||||
# @name login
|
||||
GET {{baseURL}}/api/auth/login
|
||||
|
||||
@authToken = {{login.response.body.token}}
|
||||
@currentUserId = {{login.response.body.user.id}}
|
||||
|
||||
### Get a single user
|
||||
|
||||
GET {{usersURL}}/users/{{user_id}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
@@ -0,0 +1,58 @@
|
||||
@baseURL = http://localhost:8000
|
||||
|
||||
@workspacesURL = {{baseURL}}/internal/services/workspaces/v1
|
||||
@usersURL = {{baseURL}}/internal/services/users/v1
|
||||
|
||||
@company_id = 357d0f1c-9dc9-11eb-ae20-0242ac120002
|
||||
@workspace_id = 361a5be0-f509-11eb-a69b-d9862196e0cd
|
||||
@user_id = ca68bc2a-81a4-11eb-8cf1-0242ac1e0002
|
||||
|
||||
# @name login
|
||||
POST {{baseURL}}/internal/services/console/v1/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "",
|
||||
"password": ""
|
||||
}
|
||||
|
||||
### AUTH - GET TOKEN
|
||||
@authToken = {{login.response.body.access_token.value}}
|
||||
|
||||
### USERS - GET
|
||||
GET {{usersURL}}/users/{{user_id}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### WORKSPACES - LIST
|
||||
GET {{workspacesURL}}/companies/{{company_id}}/workspaces
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
### WORKSPACES - CREATE
|
||||
POST {{workspacesURL}}/companies/{{company_id}}/workspaces
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "created workspace",
|
||||
"logo": "",
|
||||
"default": false,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
|
||||
### WORKSPACES - UPDATE
|
||||
POST {{workspacesURL}}/companies/{{company_id}}/workspaces/{{workspace_id}}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{authToken}}
|
||||
|
||||
{
|
||||
"resource": {
|
||||
"name": "updated workspace",
|
||||
"logo": "",
|
||||
"default": false,
|
||||
"archived": false
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it, jest } from "@jest/globals";
|
||||
import { CreateResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
|
||||
import { RealtimeCreated } from "../../../../../../../src/core/platform/framework/decorators";
|
||||
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
|
||||
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
|
||||
|
||||
describe("The RealtimeCreated decorator", () => {
|
||||
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeCreated({ room: "/foo/bar" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
reverseMeBaby(input: string): Promise<string> {
|
||||
return Promise.resolve(input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(0);
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should call the original method send back original result and emit event", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeCreated({ room: "/foo/bar", path: "/foo/bar/baz" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<CreateResult<string>> {
|
||||
return new CreateResult<string>("string", input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("created", {
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
entity: "oloy",
|
||||
type: "string",
|
||||
result: {
|
||||
entity: "oloy",
|
||||
type: "string",
|
||||
context: undefined,
|
||||
operation: "create",
|
||||
raw: undefined,
|
||||
} as CreateResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should emit event with path computed from function", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeCreated<string>(input => [
|
||||
{ room: ResourcePath.get(`/foo/bar/${input}`), path: "/foo/bar/baz" },
|
||||
])
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<CreateResult<string>> {
|
||||
return new CreateResult<string>("string", input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("created", {
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar/oloy"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
entity: "oloy",
|
||||
type: "string",
|
||||
result: {
|
||||
entity: "oloy",
|
||||
context: undefined,
|
||||
operation: "create",
|
||||
type: "string",
|
||||
raw: undefined,
|
||||
} as CreateResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
});
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it, jest } from "@jest/globals";
|
||||
import { DeleteResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
|
||||
import { RealtimeDeleted } from "../../../../../../../src/core/platform/framework/decorators";
|
||||
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
|
||||
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
|
||||
|
||||
describe("The RealtimeDeleted decorator", () => {
|
||||
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeDeleted({ room: "/foo/bar" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
reverseMeBaby(input: string): Promise<string> {
|
||||
return Promise.resolve(input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(0);
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should call the original method send back original result and emit event", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeDeleted({ room: "/foo/bar", path: "/foo/bar/baz" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<DeleteResult<string>> {
|
||||
return new DeleteResult<string>("string", input.split("").reverse().join(""), true);
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("deleted", {
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
entity: "oloy",
|
||||
type: "string",
|
||||
result: {
|
||||
entity: "oloy",
|
||||
context: undefined,
|
||||
operation: "delete",
|
||||
deleted: true,
|
||||
type: "string",
|
||||
} as DeleteResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should emit event with path computed from function", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeDeleted(result => [
|
||||
{ room: ResourcePath.get(`/foo/bar/${result}`), path: "/foo/bar/baz" },
|
||||
])
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<DeleteResult<string>> {
|
||||
return new DeleteResult<string>("string", input.split("").reverse().join(""), true);
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("deleted", {
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar/oloy"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
entity: "oloy",
|
||||
type: "string",
|
||||
result: {
|
||||
entity: "oloy",
|
||||
context: undefined,
|
||||
operation: "delete",
|
||||
deleted: true,
|
||||
type: "string",
|
||||
} as DeleteResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
});
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it, jest } from "@jest/globals";
|
||||
import { UpdateResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
|
||||
import { RealtimeUpdated } from "../../../../../../../src/core/platform/framework/decorators";
|
||||
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
|
||||
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
|
||||
|
||||
describe("The RealtimeUpdated decorator", () => {
|
||||
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeUpdated({ room: "/foo/bar" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
reverseMeBaby(input: string): Promise<string> {
|
||||
return Promise.resolve(input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(0);
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should call the original method send back original result and emit event", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeUpdated({ room: "/foo/bar", path: "/foo/bar/baz" })
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<UpdateResult<string>> {
|
||||
return new UpdateResult<string>("string", input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("updated", {
|
||||
entity: "oloy",
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
type: "string",
|
||||
result: {
|
||||
type: "string",
|
||||
entity: "oloy",
|
||||
affected: undefined,
|
||||
context: undefined,
|
||||
operation: "update",
|
||||
raw: undefined,
|
||||
} as UpdateResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
|
||||
it("should emit event with path computed from function", async done => {
|
||||
const emitSpy = jest.spyOn(websocketEventBus, "emit");
|
||||
|
||||
class TestMe {
|
||||
@RealtimeUpdated(result => [
|
||||
{ room: ResourcePath.get(`/foo/bar/${result}`), path: "/foo/bar/baz" },
|
||||
])
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
async reverseMeBaby(input: string): Promise<UpdateResult<string>> {
|
||||
return new UpdateResult<string>("string", input.split("").reverse().join(""));
|
||||
}
|
||||
}
|
||||
|
||||
const test = new TestMe();
|
||||
const originalSpy = jest.spyOn(test, "reverseMeBaby");
|
||||
const result = await test.reverseMeBaby("yolo");
|
||||
|
||||
expect(result.entity).toEqual("oloy");
|
||||
expect(originalSpy).toHaveBeenCalledTimes(1);
|
||||
expect(originalSpy).toHaveBeenCalledWith("yolo");
|
||||
expect(emitSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitSpy).toHaveBeenCalledWith("updated", {
|
||||
entity: "oloy",
|
||||
room: {
|
||||
name: "default",
|
||||
path: ["/foo/bar/oloy"],
|
||||
} as ResourcePath,
|
||||
resourcePath: "/foo/bar/baz",
|
||||
type: "string",
|
||||
result: {
|
||||
type: "string",
|
||||
context: undefined,
|
||||
operation: "update",
|
||||
entity: "oloy",
|
||||
affected: undefined,
|
||||
raw: undefined,
|
||||
} as UpdateResult<string>,
|
||||
});
|
||||
|
||||
emitSpy.mockRestore();
|
||||
done();
|
||||
});
|
||||
});
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
import "reflect-metadata";
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import {
|
||||
buildSelectQuery,
|
||||
buildComparison,
|
||||
buildIn,
|
||||
} from "../../../../../../../../../src/core/platform/services/database/services/orm/connectors/cassandra/query-builder";
|
||||
import { ChannelMemberNotificationPreference } from "../../../../../../../../../src/services/notifications/entities/channel-member-notification-preferences";
|
||||
|
||||
describe("The QueryBuilder module", () => {
|
||||
describe("The buildSelectQuery function", () => {
|
||||
it("should build a valid query from primary key parameters", () => {
|
||||
const filters = {
|
||||
company_id: "comp1",
|
||||
channel_id: "chan1",
|
||||
};
|
||||
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
|
||||
ChannelMemberNotificationPreference,
|
||||
filters,
|
||||
{},
|
||||
{ keyspace: "twake" },
|
||||
);
|
||||
|
||||
expect(result).toEqual(
|
||||
"SELECT * FROM twake.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should build a valid query from primary key parameters and comparison", () => {
|
||||
const filters = {
|
||||
company_id: "comp1",
|
||||
channel_id: "chan1",
|
||||
};
|
||||
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
|
||||
ChannelMemberNotificationPreference,
|
||||
filters,
|
||||
{
|
||||
$lt: [["last_read", 1000]],
|
||||
},
|
||||
{ keyspace: "twake" },
|
||||
);
|
||||
|
||||
expect(result).toEqual(
|
||||
"SELECT * FROM twake.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1 AND last_read < 1000;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should build IN query from array parameters", () => {
|
||||
const filters = {
|
||||
company_id: "comp1",
|
||||
channel_id: "chan1",
|
||||
user_id: ["u1", "u2", "u3"],
|
||||
};
|
||||
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
|
||||
ChannelMemberNotificationPreference,
|
||||
filters,
|
||||
{},
|
||||
{ keyspace: "twake" },
|
||||
);
|
||||
|
||||
expect(result).toEqual(
|
||||
"SELECT * FROM twake.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1 AND user_id IN (u1,u2,u3);",
|
||||
);
|
||||
});
|
||||
|
||||
it("should not build IN query from array parameters when array is empty", () => {
|
||||
const filters = {
|
||||
company_id: "comp1",
|
||||
channel_id: "chan1",
|
||||
user_id: [],
|
||||
};
|
||||
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
|
||||
ChannelMemberNotificationPreference,
|
||||
filters,
|
||||
{},
|
||||
{ keyspace: "twake" },
|
||||
);
|
||||
|
||||
expect(result).toEqual(
|
||||
"SELECT * FROM twake.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1;",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("The buildComparison function", () => {
|
||||
it("should create a valid < string", () => {
|
||||
expect(
|
||||
buildComparison({
|
||||
$lt: [["foo", 1]],
|
||||
}),
|
||||
).toContain("foo < 1");
|
||||
|
||||
const result = buildComparison({
|
||||
$lt: [
|
||||
["foo", 1],
|
||||
["bar", 2],
|
||||
],
|
||||
});
|
||||
|
||||
expect(result).toContain("foo < 1");
|
||||
expect(result).toContain("bar < 2");
|
||||
});
|
||||
|
||||
it("should create a valid <= string", () => {
|
||||
expect(
|
||||
buildComparison({
|
||||
$lte: [["foo", 1]],
|
||||
}),
|
||||
).toContain("foo <= 1");
|
||||
|
||||
const result = buildComparison({
|
||||
$lte: [
|
||||
["foo", 1],
|
||||
["bar", 2],
|
||||
],
|
||||
});
|
||||
|
||||
expect(result).toContain("foo <= 1");
|
||||
expect(result).toContain("bar <= 2");
|
||||
});
|
||||
|
||||
it("should create a valid > string", () => {
|
||||
expect(
|
||||
buildComparison({
|
||||
$gt: [["foo", 1]],
|
||||
}),
|
||||
).toContain("foo > 1");
|
||||
|
||||
const result = buildComparison({
|
||||
$gt: [
|
||||
["foo", 1],
|
||||
["bar", 2],
|
||||
],
|
||||
});
|
||||
|
||||
expect(result).toContain("foo > 1");
|
||||
expect(result).toContain("bar > 2");
|
||||
});
|
||||
|
||||
it("should create a valid >= string", () => {
|
||||
expect(
|
||||
buildComparison({
|
||||
$gte: [["foo", 1]],
|
||||
}),
|
||||
).toContain("foo >= 1");
|
||||
|
||||
const result = buildComparison({
|
||||
$gte: [
|
||||
["foo", 1],
|
||||
["bar", 2],
|
||||
],
|
||||
});
|
||||
|
||||
expect(result).toContain("foo >= 1");
|
||||
expect(result).toContain("bar >= 2");
|
||||
});
|
||||
|
||||
it("should combine conditions", () => {
|
||||
const result = buildComparison({
|
||||
$gt: [["foo", 1]],
|
||||
$gte: [["bar", 2]],
|
||||
$lt: [["baz", 3]],
|
||||
$lte: [["qix", 4]],
|
||||
});
|
||||
expect(result).toContain("foo > 1");
|
||||
expect(result).toContain("bar >= 2");
|
||||
expect(result).toContain("baz < 3");
|
||||
expect(result).toContain("qix <= 4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("The buildIn function", () => {
|
||||
it("should create a id IN (ids) string", () => {
|
||||
expect(
|
||||
buildIn({
|
||||
$in: [["id", ["1", "2", "3"]]],
|
||||
}),
|
||||
).toContain("id IN (1,2,3)");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import "reflect-metadata";
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import {
|
||||
fromMongoDbOrderable,
|
||||
toMongoDbOrderable,
|
||||
} from "../../../../../../src/core/platform/services/database/services/orm/utils";
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
import _ from "lodash";
|
||||
import { v1 as uuidv1 } from "uuid";
|
||||
|
||||
describe("The MongoDb to Orderable module", () => {
|
||||
describe("The to/from orderable function", () => {
|
||||
it("should be unique", () => {
|
||||
const uuid1 = toMongoDbOrderable(uuidv1());
|
||||
const uuid2 = toMongoDbOrderable(uuidv1());
|
||||
const uuid3 = toMongoDbOrderable(uuidv1());
|
||||
const uuid4 = toMongoDbOrderable(uuidv1());
|
||||
|
||||
expect(_.uniq([uuid1, uuid2, uuid3, uuid4]).length).toBe(4);
|
||||
});
|
||||
|
||||
it("should convert both ways", () => {
|
||||
const uuid = uuidv1();
|
||||
const orderable = toMongoDbOrderable(uuid);
|
||||
|
||||
expect(fromMongoDbOrderable(orderable)).toBe(uuid);
|
||||
expect(orderable).toBe(toMongoDbOrderable(fromMongoDbOrderable(orderable)));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import { decrypt } from "../../../../../src/core/crypto/index";
|
||||
import v2 from "../../../../../src/core/crypto/v2";
|
||||
import v1 from "../../../../../src/core/crypto/v1";
|
||||
import legacy from "../../../../../src/core/crypto/legacy";
|
||||
|
||||
describe("Encryption", () => {
|
||||
const encryptionKey = "a7c06651a7c063bb3e90c0c9a17eab88ab8977665127196a";
|
||||
|
||||
describe("The encrypt/decrypt functions", () => {
|
||||
it("should successfully describe legacy encrypted values", async () => {
|
||||
const legacyEncrypted = "encrypted_DwMLnKhuFbIanqBJPA5rcw==";
|
||||
|
||||
expect(legacy.decrypt(legacyEncrypted, encryptionKey).data).toBe("My company");
|
||||
expect(decrypt(legacyEncrypted, encryptionKey).data).toBe("My company");
|
||||
});
|
||||
|
||||
it("should successfully describe all versions", async () => {
|
||||
const myData = { key: "some data" };
|
||||
|
||||
const v1Encrypted = v1.encrypt(myData, encryptionKey);
|
||||
const v2Encrypted = v2.encrypt(myData, encryptionKey);
|
||||
|
||||
expect(v1.decrypt(v1Encrypted.data, encryptionKey).data).toMatchObject(myData);
|
||||
expect(v2.decrypt(v2Encrypted.data, encryptionKey).data).toMatchObject(myData);
|
||||
|
||||
expect(decrypt(v1Encrypted.data, encryptionKey).data).toMatchObject(myData);
|
||||
expect(decrypt(v2Encrypted.data, encryptionKey).data).toMatchObject(myData);
|
||||
});
|
||||
});
|
||||
});
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
import { describe, expect, it, jest, beforeEach, afterEach } from "@jest/globals";
|
||||
import {
|
||||
IncomingMessageQueueMessage,
|
||||
MessageQueueHandler,
|
||||
MessageQueueServiceAPI,
|
||||
MessageQueueServiceProcessor,
|
||||
} from "../../../../../../src/core/platform/services/message-queue/api";
|
||||
|
||||
describe("The MessageQueueServiceProcessor class", () => {
|
||||
let pubsubService: MessageQueueServiceAPI;
|
||||
let subscribe;
|
||||
let publish;
|
||||
let topic;
|
||||
let errorTopic;
|
||||
let outTopic;
|
||||
|
||||
beforeEach(() => {
|
||||
topic = "inputtopic";
|
||||
errorTopic = "errorTopic";
|
||||
outTopic = "outTopic";
|
||||
subscribe = jest.fn();
|
||||
publish = jest.fn();
|
||||
pubsubService = {
|
||||
publish,
|
||||
subscribe,
|
||||
} as unknown as MessageQueueServiceAPI;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("The init function", () => {
|
||||
it("should not subscribe when topics is not defined", async () => {
|
||||
subscribe.mockResolvedValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{} as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
expect(subscribe).not.toHaveBeenCalled;
|
||||
});
|
||||
|
||||
it("should not subscribe when topics.in is not defined", async () => {
|
||||
subscribe.mockResolvedValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {},
|
||||
} as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
expect(subscribe).not.toHaveBeenCalled;
|
||||
});
|
||||
|
||||
it("should subscribe when topics.in is defined", async () => {
|
||||
subscribe.mockResolvedValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
},
|
||||
} as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subscribe).toHaveBeenCalledWith(topic, expect.any(Function), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("The function handling incoming messages", () => {
|
||||
describe("When handler.validate is defined", () => {
|
||||
it("should not process data when data is not valid", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
const validate = jest.fn().mockReturnValue(false);
|
||||
const process = jest.fn().mockReturnValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
},
|
||||
validate,
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(validate).toBeCalledTimes(1);
|
||||
expect(validate).toBeCalledWith(message.data);
|
||||
expect(process).not.toHaveBeenCalled;
|
||||
});
|
||||
|
||||
it("should process data when data is valid", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
const validate = jest.fn().mockReturnValue(true);
|
||||
const process = jest.fn().mockReturnValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
},
|
||||
validate,
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(validate).toBeCalledTimes(1);
|
||||
expect(validate).toBeCalledWith(message.data);
|
||||
expect(process).toHaveBeenCalled;
|
||||
});
|
||||
});
|
||||
|
||||
describe("When processing message", () => {
|
||||
it("should not publish error when topics.error is not defined", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
const process = jest.fn().mockRejectedValue(new Error("I failed to process"));
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).not.toBeCalled;
|
||||
});
|
||||
|
||||
it("should publish error when topics.error is defined", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
const process = jest.fn().mockRejectedValue(new Error("I failed to process"));
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
error: errorTopic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).toBeCalledTimes(1);
|
||||
expect(publish).toBeCalledWith(errorTopic, expect.anything());
|
||||
});
|
||||
|
||||
it("should not publish when processing does not return result", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const process = jest.fn().mockResolvedValue(null);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
out: outTopic,
|
||||
error: errorTopic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).not.toBeCalled;
|
||||
});
|
||||
|
||||
it("should not publish when out topic is not defined", async () => {
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const process = jest.fn().mockResolvedValue(true);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
error: errorTopic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).not.toBeCalled;
|
||||
});
|
||||
|
||||
it("should publish when out topic is defined and process returns result", async () => {
|
||||
const result = "processing result";
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const process = jest.fn().mockResolvedValue(result);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
error: errorTopic,
|
||||
out: outTopic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).toBeCalledTimes(1);
|
||||
expect(publish).toBeCalledWith(
|
||||
outTopic,
|
||||
expect.objectContaining({
|
||||
data: result,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should publish error when result can not be published", async () => {
|
||||
publish.mockRejectedValue(new Error("I failed to publish"));
|
||||
const result = "processing result";
|
||||
const message = {
|
||||
data: "foo",
|
||||
} as IncomingMessageQueueMessage<string>;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const process = jest.fn().mockResolvedValue(result);
|
||||
const processor = new MessageQueueServiceProcessor(
|
||||
{
|
||||
topics: {
|
||||
in: topic,
|
||||
error: errorTopic,
|
||||
out: outTopic,
|
||||
},
|
||||
process,
|
||||
} as unknown as MessageQueueHandler<unknown, unknown>,
|
||||
pubsubService,
|
||||
);
|
||||
|
||||
await processor.init();
|
||||
const processMessage = subscribe.mock.calls[0][1];
|
||||
await processMessage(message);
|
||||
|
||||
expect(process).toBeCalledTimes(1);
|
||||
expect(process).toHaveBeenCalledWith(message.data);
|
||||
expect(publish).toBeCalledTimes(2);
|
||||
expect(publish.mock.calls[0][0]).toEqual(outTopic);
|
||||
expect(publish.mock.calls[1][0]).toEqual(errorTopic);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import * as pickUtils from "../../src/utils/pick";
|
||||
|
||||
describe("The pick utils", () => {
|
||||
describe("The pick function", () => {
|
||||
it("should return an object wich contains only the defined properties", () => {
|
||||
class TestClass {
|
||||
keep: string;
|
||||
me: string;
|
||||
skip: string;
|
||||
}
|
||||
|
||||
const keysToKeep = ["keep", "me"] as const;
|
||||
const object = { keep: "foo", me: "bar", skip: "baz" } as TestClass;
|
||||
const result = pickUtils.pick(object, ...keysToKeep);
|
||||
|
||||
expect(result).toEqual({ keep: "foo", me: "bar" });
|
||||
expect(result).not.toContain("skip");
|
||||
});
|
||||
|
||||
it("should return an empty object when input is empty", () => {
|
||||
class TestClass {
|
||||
keep: string;
|
||||
me: string;
|
||||
skip: string;
|
||||
}
|
||||
|
||||
const keysToKeep = [] as const;
|
||||
const object = { keep: "foo", me: "bar", skip: "baz" } as TestClass;
|
||||
const result = pickUtils.pick(object, ...keysToKeep);
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
+504
@@ -0,0 +1,504 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import {
|
||||
ListResult,
|
||||
OperationType,
|
||||
SaveResult,
|
||||
} from "../../../../../../../../src/core/platform/framework/api/crud-service";
|
||||
import { ChannelMemberNotificationLevel } from "../../../../../../../../src/services/channels/types";
|
||||
import { MessageNotification } from "../../../../../../../../src/services/messages/types";
|
||||
import {
|
||||
ChannelMemberNotificationPreference,
|
||||
ChannelThreadUsers,
|
||||
} from "../../../../../../../../src/services/notifications/entities";
|
||||
import { ChannelType } from "../../../../../../../../src/utils/types";
|
||||
import gr from "../../../../../../../../src/services/global-resolver";
|
||||
import { NewChannelMessageProcessor } from "../../../../../../../../src/services/notifications/services/engine/processors/new-channel-message";
|
||||
|
||||
describe("The NewChannelMessageProcessor class", () => {
|
||||
let channel_id, company_id, workspace_id, thread_id;
|
||||
let service: any;
|
||||
let processor: NewChannelMessageProcessor;
|
||||
let getUsersInThread;
|
||||
let getChannelPreferencesForUsers;
|
||||
|
||||
beforeEach(() => {
|
||||
channel_id = "channel_id";
|
||||
company_id = "company_id";
|
||||
workspace_id = "workspace_id";
|
||||
|
||||
getUsersInThread = jest.fn();
|
||||
getChannelPreferencesForUsers = jest.fn();
|
||||
|
||||
setPreferences();
|
||||
setUsersInThread();
|
||||
|
||||
service = {
|
||||
channelThreads: {
|
||||
bulkSave: jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new SaveResult<ChannelThreadUsers[]>("thread", [], OperationType.CREATE) as never,
|
||||
),
|
||||
getUsersInThread,
|
||||
},
|
||||
channelPreferences: {
|
||||
getChannelPreferencesForUsers,
|
||||
},
|
||||
};
|
||||
|
||||
gr.services = {
|
||||
notifications: service,
|
||||
} as any;
|
||||
|
||||
processor = new NewChannelMessageProcessor();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
function getMessage(newThread: boolean = false): MessageNotification {
|
||||
const message = {
|
||||
company_id,
|
||||
workspace_id,
|
||||
channel_id,
|
||||
id: "id",
|
||||
thread_id: "thread_id",
|
||||
sender: "sender",
|
||||
mentions: {
|
||||
users: [],
|
||||
},
|
||||
} as MessageNotification;
|
||||
|
||||
if (newThread) {
|
||||
// message is new thread when thread_id is not defined
|
||||
message.thread_id = undefined;
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function setPreferences(preferences: ChannelMemberNotificationPreference[] = []): void {
|
||||
getChannelPreferencesForUsers.mockResolvedValue(
|
||||
new ListResult<ChannelMemberNotificationPreference>("preferences", preferences),
|
||||
);
|
||||
}
|
||||
|
||||
function setUsersInThread(users: string[] = []) {
|
||||
getUsersInThread.mockResolvedValue(
|
||||
new ListResult<ChannelThreadUsers>(
|
||||
"users",
|
||||
users.map(
|
||||
user_id =>
|
||||
({
|
||||
company_id,
|
||||
channel_id,
|
||||
workspace_id,
|
||||
thread_id,
|
||||
user_id,
|
||||
} as ChannelThreadUsers),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("The process method", () => {
|
||||
describe("When message is a new thread", () => {
|
||||
function setNewThreadPreferences() {
|
||||
setPreferences([
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "1",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.ALL,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "2",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.MENTIONS,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "3",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.ME,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "4",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.NONE,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
it("should return undefined when there is no one to notify", async done => {
|
||||
const message = getMessage(true);
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
done();
|
||||
});
|
||||
|
||||
it("without mentions, should get the preferences for all channel members and return only the ones who want to be notified", async done => {
|
||||
const message = getMessage(true);
|
||||
setNewThreadPreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result.mentions.users).toEqual(["1"]);
|
||||
done();
|
||||
});
|
||||
|
||||
it("with @all mention, should get the preferences for all channel members and return only the ones who want to be notified", async done => {
|
||||
const message = getMessage(true);
|
||||
message.mentions.specials = ["all"];
|
||||
setNewThreadPreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result.mentions.users).toEqual(["1", "2"]);
|
||||
done();
|
||||
});
|
||||
|
||||
it("with @here mentions, should get the preferences for all channel members and return only the ones who want to be notified", async done => {
|
||||
const message = getMessage(true);
|
||||
message.mentions.specials = ["here"];
|
||||
setNewThreadPreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result.mentions.users).toEqual(["1", "2"]);
|
||||
done();
|
||||
});
|
||||
|
||||
it("with @user mentions, should get the preferences for all channel members and return only the ones who want to be notified", async done => {
|
||||
const message = getMessage(true);
|
||||
message.mentions.users = ["1", "2", "3", "4"];
|
||||
setNewThreadPreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "1",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "2",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "3",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "4",
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result.mentions.users).toEqual(["1", "2", "3"]);
|
||||
done();
|
||||
});
|
||||
|
||||
it("When message is a direct message", async done => {
|
||||
const message = getMessage(true);
|
||||
message.workspace_id = ChannelType.DIRECT;
|
||||
message.mentions.users = ["1", "2", "3", "4"];
|
||||
setNewThreadPreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "1",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "2",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "3",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.id,
|
||||
user_id: "4",
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).not.toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledWith({
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
});
|
||||
|
||||
expect(result.mentions.users).toEqual(["1", "2", "3"]);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe("When message is a response to a thread", () => {
|
||||
function setThreadResponsePreferences() {
|
||||
setPreferences([
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "1",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.ALL,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "2",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.MENTIONS,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "3",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.ME,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
user_id: "4",
|
||||
last_read: Date.now(),
|
||||
preferences: ChannelMemberNotificationLevel.NONE,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
it("should return undefined when there is no one to notify", async done => {
|
||||
const message = getMessage();
|
||||
setUsersInThread(["1", "2", "3", "4"]);
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
done();
|
||||
});
|
||||
|
||||
it("without mentions, should get the preferences for all members involved and return only the ones with preference !== NONE", async done => {
|
||||
const message = getMessage();
|
||||
setUsersInThread(["1", "2", "3", "4"]);
|
||||
setThreadResponsePreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
|
||||
expect(result.mentions.users).toEqual(["1", "2", "3"]);
|
||||
done();
|
||||
});
|
||||
|
||||
it("with @user mentions, should get the preferences for all members involved and return only the ones who want to be notified", async done => {
|
||||
const message = getMessage();
|
||||
message.mentions.users = ["1", "2", "3", "4"];
|
||||
setUsersInThread(["1", "2", "3", "4"]);
|
||||
setThreadResponsePreferences();
|
||||
const result = await processor.process(message);
|
||||
|
||||
expect(service.channelThreads.bulkSave).toBeCalledTimes(1);
|
||||
expect(service.channelThreads.bulkSave).toBeCalledWith(
|
||||
[
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: message.sender,
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: "1",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: "2",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: "3",
|
||||
},
|
||||
{
|
||||
company_id: message.company_id,
|
||||
channel_id: message.channel_id,
|
||||
thread_id: message.thread_id,
|
||||
user_id: "4",
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(service.channelThreads.getUsersInThread).toBeCalled;
|
||||
expect(service.channelPreferences.getChannelPreferencesForUsers).toBeCalledTimes(1);
|
||||
expect(result.mentions.users).toEqual(["1", "2", "3"]);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
import "reflect-metadata";
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import {
|
||||
ListResult,
|
||||
OperationType,
|
||||
SaveResult,
|
||||
} from "../../../../../../../../src/core/platform/framework/api/crud-service";
|
||||
import { MessageQueueServiceAPI } from "../../../../../../../../src/core/platform/services/message-queue/api";
|
||||
import { ChannelMemberNotificationLevel } from "../../../../../../../../src/services/channels/types";
|
||||
import {
|
||||
ChannelMemberNotificationPreference,
|
||||
ChannelThreadUsers,
|
||||
} from "../../../../../../../../src/services/notifications/entities";
|
||||
import {
|
||||
TYPE as UserNotificationBadgeType,
|
||||
UserNotificationBadge,
|
||||
} from "../../../../../../../../src/services/notifications/entities/user-notification-badges";
|
||||
import { MentionNotification } from "../../../../../../../../src/services/notifications/types";
|
||||
import { uniqueId } from "lodash";
|
||||
import { PushNotificationToUsersMessageProcessor } from "../../../../../../../../src/services/notifications/services/engine/processors/push-to-users";
|
||||
import gr from "../../../../../../../../src/services/global-resolver";
|
||||
|
||||
describe("The PushNotificationToUsersMessageProcessor class", () => {
|
||||
let channel_id, company_id, workspace_id, thread_id;
|
||||
let pubsubService: MessageQueueServiceAPI;
|
||||
let processor: PushNotificationToUsersMessageProcessor;
|
||||
let getUsersInThread;
|
||||
let getChannelPreferencesForUsers;
|
||||
let saveBadge;
|
||||
|
||||
beforeEach(async () => {
|
||||
channel_id = "channel_id";
|
||||
company_id = "company_id";
|
||||
workspace_id = "workspace_id";
|
||||
thread_id: "thread_id";
|
||||
|
||||
getUsersInThread = jest.fn();
|
||||
getChannelPreferencesForUsers = jest.fn();
|
||||
saveBadge = jest.fn();
|
||||
|
||||
setPreferences();
|
||||
setUsersInThread();
|
||||
|
||||
pubsubService = {
|
||||
publish: jest.fn(),
|
||||
} as unknown as MessageQueueServiceAPI;
|
||||
//
|
||||
const service = {
|
||||
badges: {
|
||||
save: saveBadge,
|
||||
},
|
||||
channelPreferences: {
|
||||
getChannelPreferencesForUsers,
|
||||
},
|
||||
};
|
||||
|
||||
gr.platformServices = {
|
||||
messageQueue: pubsubService,
|
||||
} as any;
|
||||
|
||||
gr.services = {
|
||||
notifications: service,
|
||||
} as any;
|
||||
processor = new PushNotificationToUsersMessageProcessor();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
function getMessage(newThread: boolean = false): MentionNotification {
|
||||
const message = {
|
||||
company_id,
|
||||
workspace_id,
|
||||
channel_id,
|
||||
message_id: "id",
|
||||
creation_date: Date.now(),
|
||||
thread_id,
|
||||
mentions: {
|
||||
users: [],
|
||||
},
|
||||
} as MentionNotification;
|
||||
|
||||
if (newThread) {
|
||||
// message is new thread when thread_id is not defined
|
||||
message.thread_id = undefined;
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
function setPreferences(preferences: ChannelMemberNotificationPreference[] = []): void {
|
||||
getChannelPreferencesForUsers.mockResolvedValue(
|
||||
new ListResult<ChannelMemberNotificationPreference>("preferences", preferences),
|
||||
);
|
||||
}
|
||||
|
||||
function setBadgeResults(badges: UserNotificationBadge[] = []): void {
|
||||
badges.forEach(badge =>
|
||||
saveBadge.mockResolvedValueOnce(
|
||||
new SaveResult(UserNotificationBadgeType, badge, OperationType.CREATE),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function setUsersInThread(users: string[] = []) {
|
||||
getUsersInThread.mockResolvedValue(
|
||||
new ListResult<ChannelThreadUsers>(
|
||||
"users",
|
||||
users.map(
|
||||
user_id =>
|
||||
({
|
||||
company_id,
|
||||
channel_id,
|
||||
workspace_id,
|
||||
thread_id,
|
||||
user_id,
|
||||
} as ChannelThreadUsers),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("The process method", () => {
|
||||
it("will fail when channel_id is not defined", async () => {
|
||||
const message = getMessage();
|
||||
delete message.channel_id;
|
||||
|
||||
await expect(processor.process(message)).rejects.toThrowError("Missing required fields");
|
||||
});
|
||||
|
||||
it("will fail when company_id is not defined", async () => {
|
||||
const message = getMessage();
|
||||
delete message.company_id;
|
||||
|
||||
await expect(processor.process(message)).rejects.toThrowError("Missing required fields");
|
||||
});
|
||||
|
||||
it("will fail when workspace_id is not defined", async () => {
|
||||
const message = getMessage();
|
||||
delete message.workspace_id;
|
||||
|
||||
await expect(processor.process(message)).rejects.toThrowError("Missing required fields");
|
||||
});
|
||||
|
||||
it("will fail when creation_date is not defined", async () => {
|
||||
const message = getMessage();
|
||||
delete message.creation_date;
|
||||
|
||||
await expect(processor.process(message)).rejects.toThrowError("Missing required fields");
|
||||
});
|
||||
|
||||
it("will do nothing when mentions is not defined", async done => {
|
||||
const message = getMessage();
|
||||
delete message.mentions;
|
||||
|
||||
await processor.process(message);
|
||||
|
||||
expect(gr.services.notifications.channelPreferences.getChannelPreferencesForUsers).not
|
||||
.toBeCalled;
|
||||
done();
|
||||
});
|
||||
|
||||
it("will do nothing when mentions.users is not defined", async done => {
|
||||
const message = getMessage();
|
||||
message.mentions = { users: undefined };
|
||||
|
||||
await processor.process(message);
|
||||
|
||||
expect(gr.services.notifications.channelPreferences.getChannelPreferencesForUsers).not
|
||||
.toBeCalled;
|
||||
done();
|
||||
});
|
||||
|
||||
it("will do nothing when mentions.users is empty", async done => {
|
||||
const message = getMessage();
|
||||
message.mentions = { users: [] };
|
||||
|
||||
await processor.process(message);
|
||||
|
||||
expect(gr.services.notifications.channelPreferences.getChannelPreferencesForUsers).not
|
||||
.toBeCalled;
|
||||
done();
|
||||
});
|
||||
|
||||
it("will keep users who did not read the channel yet", async done => {
|
||||
const message = getMessage();
|
||||
|
||||
setPreferences([
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
last_read: Date.now(),
|
||||
user_id: "1",
|
||||
preferences: ChannelMemberNotificationLevel.ALL,
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
last_read: Date.now(),
|
||||
user_id: "3",
|
||||
preferences: ChannelMemberNotificationLevel.ALL,
|
||||
},
|
||||
]);
|
||||
setBadgeResults([
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
thread_id,
|
||||
user_id: "1",
|
||||
workspace_id,
|
||||
message_id: message.message_id,
|
||||
id: uniqueId(),
|
||||
},
|
||||
{
|
||||
channel_id,
|
||||
company_id,
|
||||
thread_id,
|
||||
user_id: "3",
|
||||
workspace_id,
|
||||
message_id: message.message_id,
|
||||
id: uniqueId(),
|
||||
},
|
||||
]);
|
||||
|
||||
const lessThan = message.creation_date;
|
||||
const users = ["1", "2", "3", "4"];
|
||||
const channel = {
|
||||
channel_id,
|
||||
company_id,
|
||||
};
|
||||
message.mentions = { users };
|
||||
|
||||
await processor.process(message);
|
||||
|
||||
expect(getChannelPreferencesForUsers).toBeCalledWith(channel, users, { lessThan }, undefined);
|
||||
expect(gr.services.notifications.badges.save).toBeCalledTimes(2);
|
||||
expect(pubsubService.publish).toBeCalledTimes(2);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import { describe, expect, it, jest, beforeEach, afterEach, afterAll } from "@jest/globals";
|
||||
import { generateVideoPreview } from "../../../../../../../src/services/previews/services/files/processing/video";
|
||||
import ffmpeg, { ffprobe } from "fluent-ffmpeg";
|
||||
import { cleanFiles, getTmpFile } from "../../../../../../../src/utils/files";
|
||||
import fs from "fs";
|
||||
|
||||
jest.mock("fluent-ffmpeg");
|
||||
jest.mock("../../../../../../../src/utils/files");
|
||||
|
||||
const ffmpegMock = {
|
||||
screenshot: jest.fn().mockReturnValue({
|
||||
on: function (e, cb) {
|
||||
cb();
|
||||
return this;
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(fs, "statSync").mockReturnValue({ size: 1 } as any);
|
||||
(ffmpeg as any).mockImplementation(() => ffmpegMock);
|
||||
(cleanFiles as any).mockImplementation(() => jest.fn());
|
||||
(getTmpFile as any).mockImplementation(() => "/tmp/file");
|
||||
(ffprobe as any).mockImplementation((i, cb) => {
|
||||
cb(null, {
|
||||
streams: [
|
||||
{
|
||||
width: 320,
|
||||
height: 240,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("the generateVideoPreview function", () => {
|
||||
it("should return a promise", () => {
|
||||
const result = generateVideoPreview([]);
|
||||
expect(result).toBeInstanceOf(Promise);
|
||||
});
|
||||
|
||||
it("should attempt to create a screenshot using ffmpeg", async () => {
|
||||
await generateVideoPreview(["/foo/bar"]);
|
||||
expect(ffmpeg as any).toBeCalledWith("/foo/bar");
|
||||
});
|
||||
|
||||
it("should call ffmpeg screenshot method with the original video dimentions", async () => {
|
||||
(getTmpFile as any).mockImplementation(() => "/tmp/some-random-file");
|
||||
(ffprobe as any).mockImplementation((i, cb) => {
|
||||
cb(null, {
|
||||
streams: [
|
||||
{
|
||||
width: 500,
|
||||
height: 500,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
await generateVideoPreview(["/foo/bar"]);
|
||||
expect(ffmpegMock.screenshot).toBeCalledWith({
|
||||
count: 1,
|
||||
filename: "some-random-file.jpg",
|
||||
folder: "/tmp",
|
||||
timemarks: ["0"],
|
||||
size: "500x500",
|
||||
});
|
||||
});
|
||||
|
||||
it("should attempt to generate a temporary file", async () => {
|
||||
await generateVideoPreview(["/foo/bar"]);
|
||||
|
||||
expect(getTmpFile).toBeCalled();
|
||||
});
|
||||
|
||||
it("should attempt to clean up the temporary file in case of errors", async () => {
|
||||
const expectedError = new Error("failed to generate video preview: Error: foo");
|
||||
(ffmpeg as any).mockImplementation(() => {
|
||||
throw new Error("foo");
|
||||
});
|
||||
|
||||
(ffprobe as any).mockImplementation((i, cb) => {
|
||||
cb(null, {
|
||||
streams: [
|
||||
{
|
||||
width: 500,
|
||||
height: 500,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
await expect(generateVideoPreview(["/foo/bar"])).rejects.toThrow(expectedError);
|
||||
|
||||
expect(cleanFiles).toBeCalledWith(["/tmp/file.jpg"]);
|
||||
});
|
||||
|
||||
it("should return the thumbnail information", async () => {
|
||||
const result = await generateVideoPreview(["/foo/bar"]);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
width: 320,
|
||||
height: 240,
|
||||
type: "image/jpg",
|
||||
size: 1,
|
||||
path: "/tmp/file.jpg",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should generate thumbnails for multiple files", async () => {
|
||||
const result = await generateVideoPreview(["/foo/bar", "/foo/baz", "/foo/tar"]);
|
||||
expect(result).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("should use ffprobe to get the video dimensions", async () => {
|
||||
await generateVideoPreview(["/foo/bar"]);
|
||||
expect(ffprobe).toBeCalledWith("/foo/bar", expect.any(Function));
|
||||
});
|
||||
|
||||
it("should use 1080p as the maximum video dimensions", async () => {
|
||||
(ffprobe as any).mockImplementation((i, cb) => {
|
||||
cb(null, {
|
||||
streams: [
|
||||
{
|
||||
width: 5000,
|
||||
height: 5000,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const result = await generateVideoPreview(["/foo/bar"]);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
type: "image/jpg",
|
||||
size: 1,
|
||||
path: "/tmp/file.jpg",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should use 320x240 as the minimum video dimensions", async () => {
|
||||
(ffprobe as any).mockImplementation((i, cb) => {
|
||||
cb(null, {
|
||||
streams: [
|
||||
{
|
||||
width: 320,
|
||||
height: 180,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const result = await generateVideoPreview(["/foo/bar"]);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
width: 320,
|
||||
height: 240,
|
||||
type: "image/jpg",
|
||||
size: 1,
|
||||
path: "/tmp/file.jpg",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it, jest, beforeEach, afterEach, afterAll } from "@jest/globals";
|
||||
import { generateImageUrlPreview } from "../../../../../../../src/services/previews/services/links/processing/image";
|
||||
|
||||
import getFavicons from "get-website-favicon";
|
||||
import imageProbe from "probe-image-size";
|
||||
|
||||
jest.mock("get-website-favicon");
|
||||
jest.mock("probe-image-size");
|
||||
|
||||
beforeEach(() => {
|
||||
(imageProbe as any).mockImplementation(() => ({
|
||||
width: 320,
|
||||
height: 240,
|
||||
}));
|
||||
|
||||
(getFavicons as any).mockImplementation(() => ({
|
||||
icons: [
|
||||
{
|
||||
src: "http://foo.bar/favicon.ico",
|
||||
},
|
||||
],
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("the generateImageUrlPreview function", () => {
|
||||
it("should return a promise", () => {
|
||||
const result = generateImageUrlPreview("http://foo.bar");
|
||||
expect(result).toBeInstanceOf(Promise);
|
||||
});
|
||||
|
||||
it("should generate a preview for a given image url", async () => {
|
||||
const result = await generateImageUrlPreview("https://foo.bar/image.jpg");
|
||||
expect(result).toEqual({
|
||||
title: "image.jpg", // title should be the file name
|
||||
domain: "foo.bar",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
url: "https://foo.bar/image.jpg",
|
||||
img_height: 240,
|
||||
img_width: 320,
|
||||
description: null,
|
||||
img: "https://foo.bar/image.jpg",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return nothing in case of error", async () => {
|
||||
(imageProbe as any).mockImplementation(() => {
|
||||
throw new Error("failed to probe image");
|
||||
});
|
||||
|
||||
const result = await generateImageUrlPreview("https://foo.bar/image.jpg");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it, jest, beforeEach, afterEach, afterAll } from "@jest/globals";
|
||||
import { generateLinkPreview } from "../../../../../../../src/services/previews/services/links/processing/link";
|
||||
import { parser } from "html-metadata-parser";
|
||||
import getFavicons from "get-website-favicon";
|
||||
import imageProbe from "probe-image-size";
|
||||
|
||||
jest.mock("html-metadata-parser");
|
||||
jest.mock("get-website-favicon");
|
||||
jest.mock("probe-image-size");
|
||||
|
||||
beforeEach(() => {
|
||||
(imageProbe as any).mockImplementation(() => ({
|
||||
width: 320,
|
||||
height: 240,
|
||||
}));
|
||||
|
||||
(getFavicons as any).mockImplementation(() => ({
|
||||
icons: [
|
||||
{
|
||||
src: "http://foo.bar/favicon.ico",
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
(parser as any).mockImplementation(() => ({
|
||||
og: {
|
||||
title: "Foo",
|
||||
description: "Bar",
|
||||
image: "http://foo.bar/image.jpg",
|
||||
},
|
||||
meta: {
|
||||
title: "Foo",
|
||||
description: "Bar",
|
||||
image: "http://foo.bar/image1.jpg",
|
||||
},
|
||||
images: ["http://foo.bar/image2.jpg"],
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("the generateLinkPreview service", () => {
|
||||
it("should return a promise", () => {
|
||||
const result = generateLinkPreview("http://foo.bar");
|
||||
expect(result).toBeInstanceOf(Promise);
|
||||
});
|
||||
|
||||
it("should return a promise that resolves to a preview", async () => {
|
||||
const result = await generateLinkPreview("https://foo.bar");
|
||||
expect(result).toEqual({
|
||||
title: "Foo",
|
||||
description: "Bar",
|
||||
img: "http://foo.bar/image.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
img_width: 320,
|
||||
img_height: 240,
|
||||
domain: "foo.bar",
|
||||
url: "https://foo.bar",
|
||||
});
|
||||
});
|
||||
|
||||
it("should return a promise that resolves to undefined if no previews are found", async () => {
|
||||
(parser as any).mockImplementation(() => {
|
||||
throw new Error("failed to parse");
|
||||
});
|
||||
(getFavicons as any).mockImplementation(() => []);
|
||||
(imageProbe as any).mockImplementation(() => ({}));
|
||||
|
||||
const result = await generateLinkPreview("https://foo.bar");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should use og information as first choice", async () => {
|
||||
(parser as any).mockImplementation(() => ({
|
||||
og: {
|
||||
title: "test",
|
||||
description: "test",
|
||||
image: "http://foo.bar/test.jpg",
|
||||
},
|
||||
meta: {
|
||||
title: "test2",
|
||||
description: "test2",
|
||||
image: "http://foo.bar/test2.jpg",
|
||||
},
|
||||
images: ["http://foo.bar/test3.jpg"],
|
||||
}));
|
||||
|
||||
const result = await generateLinkPreview("https://foo.bar");
|
||||
expect(result).toEqual({
|
||||
title: "test",
|
||||
description: "test",
|
||||
img: "http://foo.bar/test.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
img_width: 320,
|
||||
img_height: 240,
|
||||
domain: "foo.bar",
|
||||
url: "https://foo.bar",
|
||||
});
|
||||
});
|
||||
|
||||
it("should use meta information as second choice", async () => {
|
||||
(parser as any).mockImplementation(() => ({
|
||||
meta: {
|
||||
title: "test2",
|
||||
description: "test2",
|
||||
image: "http://foo.bar/test2.jpg",
|
||||
},
|
||||
images: [],
|
||||
}));
|
||||
|
||||
const result = await generateLinkPreview("https://foo.bar");
|
||||
expect(result).toEqual({
|
||||
title: "test2",
|
||||
description: "test2",
|
||||
img: "http://foo.bar/test2.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
img_width: 320,
|
||||
img_height: 240,
|
||||
domain: "foo.bar",
|
||||
url: "https://foo.bar",
|
||||
});
|
||||
});
|
||||
|
||||
it("should use the first image found in the url when none are present in the og or meta information", async () => {
|
||||
(parser as any).mockImplementation(() => ({
|
||||
og: {
|
||||
title: "test",
|
||||
description: "test",
|
||||
},
|
||||
meta: {
|
||||
title: "test2",
|
||||
description: "test2",
|
||||
},
|
||||
images: ["http://foo.bar/test3.jpg", "http://foo.bar/test4.jpg"],
|
||||
}));
|
||||
|
||||
const result = await generateLinkPreview("https://foo.bar");
|
||||
expect(result).toEqual({
|
||||
title: "test",
|
||||
description: "test",
|
||||
img: "http://foo.bar/test3.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
img_width: 320,
|
||||
img_height: 240,
|
||||
domain: "foo.bar",
|
||||
url: "https://foo.bar",
|
||||
});
|
||||
});
|
||||
|
||||
it("shouldn't attempt to probe for image size when none are found", async () => {
|
||||
(parser as any).mockImplementation(() => ({
|
||||
og: {
|
||||
title: "test",
|
||||
description: "test",
|
||||
},
|
||||
meta: {
|
||||
title: "test2",
|
||||
description: "test2",
|
||||
},
|
||||
images: [],
|
||||
}));
|
||||
|
||||
await generateLinkPreview("https://foo.bar");
|
||||
expect(imageProbe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should strip www from the domain", async () => {
|
||||
const result = await generateLinkPreview("https://www.foo.bar");
|
||||
expect(result).toEqual({
|
||||
title: "Foo",
|
||||
description: "Bar",
|
||||
img: "http://foo.bar/image.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
img_width: 320,
|
||||
img_height: 240,
|
||||
domain: "foo.bar",
|
||||
url: "https://www.foo.bar",
|
||||
});
|
||||
});
|
||||
});
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import {
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
jest,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
beforeAll,
|
||||
} from "@jest/globals";
|
||||
import { LinkPreviewProcessService } from "../../../../../../../src/services/previews/services/links/processing/service";
|
||||
import { generateLinkPreview } from "../../../../../../../src/services/previews/services/links/processing/link";
|
||||
import { generateImageUrlPreview } from "../../../../../../../src/services/previews/services/links/processing/image";
|
||||
import axios from "axios";
|
||||
|
||||
jest.mock("axios");
|
||||
jest.mock("../../../../../../../src/services/previews/services/links/processing/link");
|
||||
jest.mock("../../../../../../../src/services/previews/services/links/processing/image");
|
||||
|
||||
let service: LinkPreviewProcessService;
|
||||
|
||||
beforeEach(async () => {
|
||||
(axios as any).mockImplementation(() => ({
|
||||
headers: {
|
||||
"content-type": "text/html",
|
||||
},
|
||||
}));
|
||||
|
||||
(generateLinkPreview as any).mockImplementation(() => ({
|
||||
title: "Foo",
|
||||
description: "Bar",
|
||||
img: "http://foo.bar/image.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
}));
|
||||
|
||||
(generateImageUrlPreview as any).mockImplementation(() => ({
|
||||
title: "image.jpg",
|
||||
description: null,
|
||||
img: "http://foo.bar/image.jpg",
|
||||
favicon: "http://foo.bar/favicon.ico",
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
service = await new LinkPreviewProcessService().init();
|
||||
});
|
||||
|
||||
describe("the LinkPreviewProcessService service", () => {
|
||||
it("should return a promise", () => {
|
||||
const result = service.generatePreviews(["http://foo.bar"]);
|
||||
expect(result).toBeInstanceOf(Promise);
|
||||
});
|
||||
|
||||
it("should call generateLinkPreview when it's a html page", async () => {
|
||||
(axios as any).mockImplementation(() => ({
|
||||
headers: {
|
||||
"content-type": "text/html",
|
||||
},
|
||||
}));
|
||||
|
||||
await service.generatePreviews(["http://foo.bar"]);
|
||||
expect(generateLinkPreview).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should call generateImageUrlPreview when it's an image", async () => {
|
||||
(axios as any).mockImplementation(() => ({
|
||||
headers: {
|
||||
"content-type": "image/jpeg",
|
||||
},
|
||||
}));
|
||||
|
||||
await service.generatePreviews(["http://foo.bar/image.jpg"]);
|
||||
expect(generateImageUrlPreview).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should skip if the url content is not supported", async () => {
|
||||
(axios as any).mockImplementation(() => ({
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
}));
|
||||
|
||||
await service.generatePreviews(["http://foo.bar"]);
|
||||
expect(generateLinkPreview).not.toHaveBeenCalled();
|
||||
expect(generateImageUrlPreview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// should filter null values
|
||||
it("should filter null values", async () => {
|
||||
(axios as any).mockImplementation(() => ({
|
||||
headers: {
|
||||
"content-type": "text/html",
|
||||
},
|
||||
}));
|
||||
|
||||
(generateLinkPreview as any).mockImplementation(() => null);
|
||||
|
||||
const result = await service.generatePreviews(["http://foo.bar", "http://foo.xyz"]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user