ToolJet/server/test/controllers/tooljet_db.e2e-spec.ts
Akshay 602b1b4ad3
Feature: Tooljet Database (#4951)
* wip

* internal db per workspace

* fix async query

* feat: add storage layer route

* feat: add drawer component

* feat: add react-table to load data

* feat: add columns form

* feat: add create column form, create row form

* feat: add postgrest js

* add tooljet db controller to proxy requests to postgrest

* util: add postgrest filter builder helper utility

* feat: add filter popover

* use helper utility for building query

* add sortable filters

* add box shadow for filter popup

* use overlay trigger

* use react select

* add new column addition

* add dropdown for table header, table list

* Move filter.jsx

* feat: add sort popover

* feat: add postgrest js .order fn

* setup tooljetdb with restricted grants for users

* make db schemas added loaded dynamically on postgrest server

* fix query

* sign jwt token to auth user at postgrest

* update db schema user with workspace

* chore: add table listing

* update data and columns from api

* feat: add context api for sharing data

* add ability to create table, view tables and add columns

* use columns for sort from context api

* fix ormconfig

* feat: add table listing integration

* feat: add create table integration

* fix for rds deployment

* add internal table translation instead of schema

* remove tooljetdb as a datasource

* wrap placeholder on proxy query

* add active workspace guard

* scope tooljetdb by workspace

* update active workspace guard

* seperate proxy related concerns to different service

* make use of org id param

* rename storage layer to tooljet databse

* update specs

* feat: Update list when new table added

* feat: add create column

* chore: add orgId to url + misc changes

* chore: move popover to separate file

* remove unused var

* rename files

* feat: add multiple columns

* feat: add new row

* removes postgrest-js from pkg lock

* feat: add row data

* feat: add sorting

* feat: allow row deletion

* feat: add search

* feat: add filtering

* feat: add edit mode

* feat: add columns while edit table

* add view table action

* update setup for column constraint

* fix query

* integrate view_table, primary key field

* render toogle for boolean data type

* update view table query for primary key

* fetch metadata refactor

* add capability to set default values

* feat: allow deletion of record based on primary key

* feat: add default value while creating column

* send query from sort & filter component

* css changes

* allow empty data

* add requested changes

* add err message

* add common fn

* allow sort + filter

* remove unwanted defaults key

* css changes

* add more operators

* dark mode fixes

* add drawer footer

* add loader for list tables

* add dashboard design changes

* design changes

* add capability to drop table and delete column

* add breadcrumbs

* design changes

* add profile

* refactor tooljetdb controller

* update routes

* add empty page changes

* delete column fix

* fix delete column

* design changes

* fetch tables post delete

* homepage changes

* hide ellipsis on hover

* add org settings page

* add edit + create org

* add notification center

* fix: group permissions switch issue

* add logo

* remove anchor tag

* fix merge conflicts

* css changes

* add err boundary

* setup query editor

* css changes

* fix: merge conflicts

* add menuPortal prop to filterform and sort form

* fix seed

* fix: build

* design changes

* design changes + refactor code

* fix imports

* fix: drawer issue on delete table

* add search box changes

* fix: tablename max-length 255

* fix: set newly created table as selected item

* remove edit column option

* added badges to enterprise only features

* disable edit column

* table styles

* fix: popover position, placeholder default

* fix: display boolean values in table

* fix: tooljet database default type values

* css changes

* add query manager for tooljet db with create and list row

* dark mode fixes

* remove Header component

* add ability to delete tooljetdb rows from query manager

* add ability to update tooljetdb rows

* dark mode fixes

* css changes

* display actions icon on hover

* folder onclick change

* add empty page styles

* fix proxy requests

* feat: randomize icon creation

* add max items per page prop for pagination

* removes unwanted position attr

* add table name validation + disable submit btn while api fetch

* [Bugfix] internal storage toast  | trigger toasts for running preview db queries (#5019)

* resolves: no toasts are fired when preview query is run for db queries

* fire success toast for created and no content status text for query success

* remove invalid migration

* skip migration if tooljet db already created

* fix: app clone icon param

* fix: show confirmation box if filter options are empty in query (#5021)

* for now: show native confirmation box of the brower to confirm the delete all query

* typo

* Revert "typo"

This reverts commit b5ce5ed889.

* cleaned

* cleaned

* show confirmation box if filter options are empty in query

* [Refactor/Bugfix] database query (#5028)

* refactored list rows operations

* remove unwanted cls

* refactor create row

* reafactored update rows

* refactored delete rows

* padding fix for tj-query

* add static templates

* review changes

* remove unused file

* Chore: tooljetdb render setup (#5033)

* add postgrest for render preview deploy

* pin version

* add healthCheckPath

* remove health check

* handle database url parsing db params

* add defaults for tooljetdb env

* fix hostname

* handle env in migration files

* refactor dbconfig build

* fix pg db usage

* add parsed env context

* add tooljetdb env

* refactor db config utils

Co-authored-by: gandharv <gandharvkumargarg@gmail.com>
Co-authored-by: Shubhendra <withshubh@gmail.com>
Co-authored-by: Arpit <arpitnath42@gmail.com>
2022-12-23 02:09:57 +05:30

270 lines
9.2 KiB
TypeScript

import * as request from 'supertest';
import { INestApplication } from '@nestjs/common';
import { authHeaderForUser, clearDB, createUser, createNestAppInstanceWithEnvMock } from '../test.helper';
import { getManager, QueryFailedError } from 'typeorm';
import { InternalTable } from 'src/entities/internal_table.entity';
import { mocked } from 'ts-jest/utils';
import got from 'got';
jest.mock('got');
const mockedGot = mocked(got);
describe('Tooljet DB controller', () => {
let nestApp: INestApplication;
let mockConfig;
beforeEach(async () => {
await clearDB();
});
beforeAll(async () => {
({ app: nestApp, mockConfig } = await createNestAppInstanceWithEnvMock());
});
afterEach(async () => {
jest.resetAllMocks();
jest.clearAllMocks();
const internalTables = await getManager().find(InternalTable);
for (const internalTable of internalTables) {
await getManager('tooljetDb').query(`TRUNCATE "${internalTable.id}" RESTART IDENTITY CASCADE;`);
}
});
describe('GET /api/tooljet_db/:organizationId/proxy/*', () => {
it('should allow only authenticated users', async () => {
const mockId = 'c8657683-b112-4a36-9ce7-79ebf68c8098';
await request(nestApp.getHttpServer()).get(`/api/tooljet_db/${mockId}/proxy/table_name`).expect(401);
});
it('should allow only active users in workspace', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const archivedUserData = await createUser(nestApp, {
email: 'developer@tooljet.io',
groups: ['all_users'],
status: 'archived',
organization: adminUserData.organization,
});
await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/${archivedUserData.organization.id}/proxy/table_name`)
.set('Authorization', authHeaderForUser(archivedUserData.user))
.expect(401);
});
it('should throw error when internal table is not found', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const response = await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/${adminUserData.organization.id}/proxy/\${table_name}`)
.set('Authorization', authHeaderForUser(adminUserData.user));
const { message, statusCode } = response.body;
expect(message).toBe('Internal table not found: table_name');
expect(statusCode).toBe(404);
});
xit('should replace the table names and proxy requests to postgrest host', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
if (key === 'PGRST_HOST') {
return 'http://postgrest-mock';
} else {
return process.env[key];
}
});
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const actorsTable = getManager().create(InternalTable, {
tableName: 'actors',
organizationId: adminUserData.organization.id,
});
await actorsTable.save();
const filmsTable = getManager().create(InternalTable, {
tableName: 'films',
organizationId: adminUserData.organization.id,
});
await filmsTable.save();
const postgrestResponse = jest.fn();
postgrestResponse.mockImplementation(() => {
return {
json: () => {
return {
root: [],
};
},
};
});
mockedGot.mockImplementationOnce(postgrestResponse);
const response = await request(nestApp.getHttpServer())
.get(
`/api/tooljet_db/${adminUserData.organization.id}/proxy/\${actors}?select=first_name,last_name,\${films}(title)}`
)
.set('Authorization', authHeaderForUser(adminUserData.user));
// expect(postgrestResponse).toBeCalledWith(`http://localhost:3001/${actorsTable.id}?select=first_name,last_name,${filmsTable.id}(title)`, expect.anything());
const { message, statusCode } = response.body;
expect(message).toBe('Internal table not found: table_name');
expect(statusCode).toBe(404);
});
});
describe('GET /api/tooljet_db/perform', () => {
it('should allow only authenticated users', async () => {
const mockId = 'c8657683-b112-4a36-9ce7-79ebf68c8098';
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${mockId}/perform`)
.send({ action: 'view_tables' })
.expect(401);
});
it('should allow only active users in workspace', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const archivedUserData = await createUser(nestApp, {
email: 'developer@tooljet.io',
groups: ['all_users'],
status: 'archived',
organization: adminUserData.organization,
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${archivedUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(archivedUserData.user))
.expect(401);
});
it('should throw error when action is not defined', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const response = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user));
const { message, statusCode } = response.body;
expect(message).toBe('Action not defined');
expect(statusCode).toBe(400);
});
it('should be able to create table', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const { statusCode } = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'test_table',
columns: [{ column_name: 'type', data_type: 'varchar' }],
});
expect(statusCode).toBe(201);
const internalTables = await getManager().find(InternalTable);
expect(internalTables).toHaveLength(1);
const [createdInternalTable] = internalTables;
expect(createdInternalTable.tableName).toEqual('test_table');
await expect(
getManager('tooljetDb').query(`SELECT * from "${createdInternalTable.id}"`)
).resolves.not.toThrowError(QueryFailedError);
});
it('should be able to view tables', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'actors',
columns: [{ column_name: 'name', data_type: 'varchar' }],
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'films',
columns: [{ column_name: 'name', data_type: 'varchar' }],
});
const { statusCode, body } = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({ action: 'view_tables' });
const tableNames = body.result.map((table) => table.table_name);
expect(statusCode).toBe(201);
expect(new Set(tableNames)).toEqual(new Set(['actors', 'films']));
});
it('should be able to add column to table', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'test_table',
columns: [{ column_name: 'type', data_type: 'varchar' }],
});
const internalTable = await getManager().findOne(InternalTable, { where: { tableName: 'test_table' } });
expect(internalTable.tableName).toEqual('test_table');
await expect(getManager('tooljetDb').query(`SELECT name from "${internalTable.id}"`)).rejects.toThrowError(
QueryFailedError
);
const { statusCode } = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/${adminUserData.organization.id}/perform`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'add_column',
table_name: 'test_table',
column: { column_name: 'name', data_type: 'varchar' },
});
expect(statusCode).toBe(201);
await expect(getManager('tooljetDb').query(`SELECT name from "${internalTable.id}"`)).resolves.not.toThrowError(
QueryFailedError
);
});
});
afterAll(async () => {
await nestApp.close();
});
});