|
1 | 1 | import { eq } from 'drizzle-orm'; |
2 | 2 | import { StatusCodes } from 'http-status-codes'; |
| 3 | +import { AddressInfo } from 'net'; |
| 4 | +import { v4 } from 'uuid'; |
| 5 | +import { WebSocket } from 'ws'; |
3 | 6 |
|
4 | 7 | import type { FastifyInstance } from 'fastify'; |
5 | 8 |
|
6 | | -import { FolderItemFactory, HttpMethod } from '@graasp/sdk'; |
| 9 | +import { FolderItemFactory, HttpMethod, PermissionLevel } from '@graasp/sdk'; |
7 | 10 |
|
8 | 11 | import build, { |
9 | 12 | clearDatabase, |
@@ -72,4 +75,56 @@ describe('Page routes tests', () => { |
72 | 75 | }); |
73 | 76 | }); |
74 | 77 | }); |
| 78 | + |
| 79 | + describe('GET /items/pages/ws', () => { |
| 80 | + it('Throws if signed out', async () => { |
| 81 | + const response = await app.inject({ |
| 82 | + method: HttpMethod.Get, |
| 83 | + url: { protocol: 'ws', pathname: `/items/pages/${v4()}/ws` }, |
| 84 | + }); |
| 85 | + |
| 86 | + expect(response.statusCode).toBe(StatusCodes.UNAUTHORIZED); |
| 87 | + }); |
| 88 | + |
| 89 | + it('Throws if id is incorrect', async () => { |
| 90 | + const response = await app.inject({ |
| 91 | + method: HttpMethod.Get, |
| 92 | + path: { |
| 93 | + protocol: 'ws', |
| 94 | + pathname: '/items/pages/wrong-id/ws', |
| 95 | + }, |
| 96 | + }); |
| 97 | + |
| 98 | + expect(response.statusCode).toBe(StatusCodes.BAD_REQUEST); |
| 99 | + }); |
| 100 | + |
| 101 | + it('Allow access', async () => { |
| 102 | + const { |
| 103 | + actor, |
| 104 | + items: [item], |
| 105 | + } = await seedFromJson({ |
| 106 | + items: [{ memberships: [{ account: 'actor', permission: PermissionLevel.Write }] }], |
| 107 | + }); |
| 108 | + assertIsDefined(actor); |
| 109 | + mockAuthenticate(actor); |
| 110 | + |
| 111 | + // start server to correctly listen to websockets |
| 112 | + await app.listen(); |
| 113 | + await app.ready(); |
| 114 | + const port = (app.server.address() as AddressInfo)!.port; |
| 115 | + const ws = new WebSocket(`http://localhost:${port}/items/pages/${item.id}/ws`); |
| 116 | + |
| 117 | + await new Promise((done, reject) => { |
| 118 | + ws.on('error', (e) => { |
| 119 | + console.log(e); |
| 120 | + reject(new Error('should not throw')); |
| 121 | + }); |
| 122 | + |
| 123 | + ws.on('message', () => { |
| 124 | + // should be able to receive messages |
| 125 | + done(true); |
| 126 | + }); |
| 127 | + }); |
| 128 | + }); |
| 129 | + }); |
75 | 130 | }); |
0 commit comments