aboutsummaryrefslogtreecommitdiffstats
path: root/app/Controllers/Http/WorkspaceController.ts
blob: 4dff4dfe6e44609304ef4d4cbf8723e2d50735bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import { validator, schema } from '@ioc:Adonis/Core/Validator';
import Workspace from 'App/Models/Workspace';
import { v4 as uuid } from 'uuid';

const createSchema = schema.create({
  name: schema.string(),
});

const editSchema = schema.create({
  name: schema.string(),
});

const deleteSchema = schema.create({
  id: schema.string(),
});

export default class WorkspacesController {
  // Create a new workspace for user
  public async create({ request, response, auth }: HttpContextContract) {
    // @ts-expect-error Property 'user' does not exist on type 'HttpContextContract'.
    const user = auth.user ?? request.user;

    if (!user) {
      return response.unauthorized('Missing or invalid api token');
    }

    // Validate user input
    let data;
    try {
      data = await request.validate({ schema: createSchema });
    } catch (error) {
      return response.status(401).send({
        message: 'Invalid POST arguments',
        messages: error.messages,
        status: 401,
      });
    }

    // Get new, unused uuid
    let workspaceId;
    do {
      workspaceId = uuid();
    } while (
      // eslint-disable-next-line unicorn/no-await-expression-member, no-await-in-loop
      (await Workspace.query().where('workspaceId', workspaceId)).length > 0
    );

    // eslint-disable-next-line unicorn/no-await-expression-member
    const order = (await user.related('workspaces').query()).length;

    await Workspace.create({
      userId: user.id,
      workspaceId,
      name: data.name,
      order,
      services: JSON.stringify([]),
      data: JSON.stringify(data),
    });

    return response.send({
      userId: user.id,
      name: data.name,
      id: workspaceId,
      order,
      workspaces: [],
    });
  }

  public async edit({ request, response, auth, params }: HttpContextContract) {
    // @ts-expect-error Property 'user' does not exist on type 'HttpContextContract'.
    const user = auth.user ?? request.user;

    if (!user) {
      return response.unauthorized('Missing or invalid api token');
    }

    // Validate user input
    try {
      await request.validate({ schema: editSchema });
    } catch (error) {
      return response.status(401).send({
        message: 'Invalid POST arguments',
        messages: error.messages,
        status: 401,
      });
    }

    const data = request.all();
    const { id } = params;

    // Update data in database
    await Workspace.query()
      .where('workspaceId', id)
      .where('userId', user.id)
      .update({
        name: data.name,
        services: JSON.stringify(data.services),
      });

    // Get updated row
    const workspace = await Workspace.query()
      .where('workspaceId', id)
      .where('userId', user.id)
      .firstOrFail();

    return response.send({
      id: workspace.workspaceId,
      name: data.name,
      order: workspace.order,
      services: data.services,
      userId: user.id,
    });
  }

  public async delete({ response, auth, params }: HttpContextContract) {
    // @ts-expect-error Property 'user' does not exist on type 'HttpContextContract'.
    const user = auth.user ?? request.user;

    if (!user) {
      return response.unauthorized('Missing or invalid api token');
    }

    // Validate user input
    let data;
    try {
      data = await validator.validate({
        data: params,
        schema: deleteSchema,
      });
    } catch (error) {
      return response.status(401).send({
        message: 'Invalid arguments',
        messages: error.messages,
        status: 401,
      });
    }

    const { id } = data;

    // Update data in database
    await Workspace.query()
      .where('workspaceId', id)
      .where('userId', user.id)
      .delete();

    return response.send({
      message: 'Successfully deleted workspace',
    });
  }

  // List all workspaces a user has created
  public async list({ request, response, auth }: HttpContextContract) {
    // @ts-expect-error Property 'user' does not exist on type 'HttpContextContract'.
    const user = auth.user ?? request.user;

    if (!user) {
      return response.unauthorized('Missing or invalid api token');
    }

    const workspaces = await user.related('workspaces').query();
    // Convert to array with all data Franz wants
    let workspacesArray: object[] = [];
    if (workspaces) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      workspacesArray = workspaces.map((workspace: any) => ({
        id: workspace.workspaceId,
        name: workspace.name,
        order: workspace.order,
        services:
          typeof workspace.services === 'string'
            ? JSON.parse(workspace.services)
            : workspace.services,
        userId: user.id,
      }));
    }

    return response.send(workspacesArray);
  }
}