Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more tests #36

Merged
merged 9 commits into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/api/ShlinkApiProxyClient.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import type {
} from '@shlinkio/shlink-js-sdk/api-contract';

export class ShlinkApiProxyClient implements ShlinkApiClient {
constructor(private readonly serverId: string) {
constructor(private readonly serverId: string, private readonly fetch = window.fetch.bind(window)) {
}

createShortUrl(options: ShlinkCreateShortUrlData): Promise<ShlinkShortUrl> {
Expand Down Expand Up @@ -126,7 +126,7 @@ export class ShlinkApiProxyClient implements ShlinkApiClient {
}

private async performRequest<T>(action: string, ...args: unknown[]): Promise<T> {
const resp = await fetch(`/server/${this.serverId}/shlink-api/${action}`, {
const resp = await this.fetch(`/server/${this.serverId}/shlink-api/${action}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import { json } from '@remix-run/node';
import { ShlinkApiClient } from '@shlinkio/shlink-js-sdk';
import { NodeHttpClient } from '@shlinkio/shlink-js-sdk/node';
import { appDataSource } from '../db/data-source.server';
import { ServerEntity } from '../entities/Server';
import type { Server } from '../entities/Server';
import { ServersService } from '../servers/ServersService.server';

Check warning on line 6 in app/routes/server.$serverId.shlink-api.$method.ts

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.shlink-api.$method.ts#L5-L6

Added lines #L5 - L6 were not covered by tests

type Callback = (...args: unknown[]) => unknown;

Expand All @@ -19,17 +19,18 @@
return args.length >= callback.length;
}

export async function action({ params, request }: ActionFunctionArgs) {
export async function action(
{ params, request }: ActionFunctionArgs,
serversService = new ServersService(),
createApiClient = (server: Server) => new ShlinkApiClient(new NodeHttpClient(), server),
) {

Check warning on line 26 in app/routes/server.$serverId.shlink-api.$method.ts

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.shlink-api.$method.ts#L22-L26

Added lines #L22 - L26 were not covered by tests
try {
const { method, serverId } = params;
const { method, serverId = '' } = params;

Check warning on line 28 in app/routes/server.$serverId.shlink-api.$method.ts

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.shlink-api.$method.ts#L28

Added line #L28 was not covered by tests

// TODO Make sure current user has access for this server
const server = await appDataSource.manager.findOneBy(ServerEntity, { publicId: serverId });
if (!server) {
return json({}, 404); // TODO Return some useful info in Problem Details format
}
const server = await serversService.getByPublicId(serverId);

Check warning on line 31 in app/routes/server.$serverId.shlink-api.$method.ts

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.shlink-api.$method.ts#L31

Added line #L31 was not covered by tests

const client = new ShlinkApiClient(new NodeHttpClient(), server);
const client = createApiClient(server);

Check warning on line 33 in app/routes/server.$serverId.shlink-api.$method.ts

View check run for this annotation

Codecov / codecov/patch

app/routes/server.$serverId.shlink-api.$method.ts#L33

Added line #L33 was not covered by tests
if (!method || !actionInApiClient(method, client)) {
return json({}, 404); // TODO Return some useful info in Problem Details format
}
Expand All @@ -48,7 +49,7 @@

return json(response);
} catch (e) {
console.error(e);

Check warning on line 52 in app/routes/server.$serverId.shlink-api.$method.ts

View workflow job for this annotation

GitHub Actions / ci / lint (npm run lint)

Unexpected console statement
return json({}, 500); // TODO Return some useful info in Problem Details format
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { ActionFunctionArgs } from '@remix-run/node';
import { json } from '@remix-run/node';
import { TagsService } from '../tags/TagsService.server';

export async function action({ params, request }: ActionFunctionArgs, tagsService = new TagsService()) {
Expand All @@ -10,6 +9,5 @@ export async function action({ params, request }: ActionFunctionArgs, tagsServic

await tagsService.updateTagColors({ colors, userId, serverPublicId });

// TODO Return new colors
return json({});
return new Response(null, { status: 204 });
}
17 changes: 17 additions & 0 deletions app/servers/ServersService.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { EntityManager } from 'typeorm';
import { appDataSource } from '../db/data-source.server';
import type { Server } from '../entities/Server';
import { ServerEntity } from '../entities/Server';

export class ServersService {
constructor(private readonly em: EntityManager = appDataSource.manager) {}

public async getByPublicId(publicId: string): Promise<Server> {
const server = await this.em.findOneBy(ServerEntity, { publicId });
if (!server) {
throw new Error(`Server with public ID ${publicId} not found`);
}

return server;
}
}
42 changes: 28 additions & 14 deletions app/tags/TagsService.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export type UpdateTagColorsParam = FindTagsParam & {
colors: Record<string, string>;
};

type ServerAndUserResult = {
server: Server | null;
user: User | null;
};

export class TagsService {
constructor(private readonly em: EntityManager = appDataSource.manager) {
}
Expand Down Expand Up @@ -42,22 +47,31 @@ export class TagsService {
return;
}

// FIXME MS SQL Server does not support upsert
await this.em.transaction((em) => em.upsert(
TagEntity,
Object.entries(colors).map(([tag, color]) => ({
tag,
color: color as string,
user,
server,
})),
['tag', 'user', 'server'],
));
const isMs = this.em.connection.options.type === 'mssql';
await this.em.transaction((em): Promise<unknown> => {
if (!isMs) {
return em.upsert(
TagEntity,
Object.entries(colors).map(([tag, color]) => ({ tag, color, user, server })),
['tag', 'user', 'server'],
);
}

// MS SQL Server does not support upsert
return Promise.all(Object.entries(colors).map(async ([tag, color]) => {
const tagEntity = await em.findOneBy(TagEntity, { user, server, tag }).then(
// If a tag was not found, create it
(result) => result ?? em.create(TagEntity, { user, server, tag, color }),
);

tagEntity.color = color;

await em.save(tagEntity);
}));
});
}

private async resolveServerAndUser(
{ userId, serverPublicId }: FindTagsParam,
): Promise<{ server: Server | null; user: User | null }> {
private async resolveServerAndUser({ userId, serverPublicId }: FindTagsParam): Promise<ServerAndUserResult> {
const [server, user] = await Promise.all([
serverPublicId ? this.em.findOneBy(ServerEntity, { publicId: serverPublicId }) : null,
this.em.findOneBy(UserEntity, { id: userId }),
Expand Down
8 changes: 6 additions & 2 deletions app/tags/TagsStorage.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
}

export class TagsStorage implements TagColorsStorage {
constructor(private colors: Record<string, string>, private readonly saveEndpoint: string) {
constructor(
private colors: Record<string, string>,
private readonly saveEndpoint: string,
private readonly fetch = window.fetch.bind(window),
) {
}

getTagColors(): Record<string, string> {
Expand All @@ -30,10 +34,10 @@
return;
}

fetch(this.saveEndpoint, {
this.fetch(this.saveEndpoint, {
method: 'POST',
body: JSON.stringify(changedColors),
headers: { 'Content-Type': 'application/json' },
}).catch(console.error); // TODO Handle error

Check warning on line 41 in app/tags/TagsStorage.client.ts

View workflow job for this annotation

GitHub Actions / ci / lint (npm run lint)

Unexpected console statement
}
}
2 changes: 1 addition & 1 deletion app/utils/env.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const supportedDbEngines = ['mysql', 'postgres', 'mariadb', 'sqlite', 'mssql'] a
export type DbEngine = typeof supportedDbEngines[number];

const envVariables = z.object({
NODE_ENV: z.enum(['production', 'development']).optional(),
NODE_ENV: z.enum(['production', 'development', 'test']).optional(),

// Database connection options
SHLINK_DASHBOARD_DB_DRIVER: z.enum(supportedDbEngines).optional(),
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ services:
- ./:/home/shlink-dashboard
ports:
- "3005:3005"
- "24678:24678" # Vite dev server web socket port
links:
- shlink_dashboard_db_postgres
environment:
Expand Down
Loading
Loading