# vuurrood-sockets

> vuurrood sockets package for api

Latest version **2.2.20** (published 2022-10-17) · ISC license · 0 weekly downloads

## Install

```sh
npm install vuurrood-sockets
pnpm add vuurrood-sockets
yarn add vuurrood-sockets
bun add vuurrood-sockets
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.2.20 |
| Published | 2022-10-17 |
| First published | 2022-05-11 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 4 |
| Unpacked size | 50.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | vuurrood |
| Maintainers | nelte |

## Links

- npm: https://www.npmjs.com/package/vuurrood-sockets
- Repository: https://gitlab.com/vuurrood/packages/vuurrood-sockets
- Homepage: https://gitlab.com/vuurrood/packages/vuurrood-sockets#readme
- Issues: https://gitlab.com/vuurrood/packages/vuurrood-sockets/issues
- npm.io page: https://npm.io/package/vuurrood-sockets

## Dependencies (4)

- [cron](https://npm.io/package/cron.md) ^2.0.0
- [nanoid](https://npm.io/package/nanoid.md) ^3.3.4
- [socket.io](https://npm.io/package/socket.io.md) ^4.5.0
- [@types/express](https://npm.io/package/@types/express.md) ^4.17.13

## Recent versions

- 2.2.20 (latest) — 2022-10-17
- 2.2.19 — 2022-10-17
- 2.2.18 — 2022-10-17
- 2.2.17 — 2022-08-09
- 2.2.16 — 2022-08-09
- 2.2.15 — 2022-08-09
- 2.2.14 — 2022-08-09
- 2.2.13 — 2022-08-09
- 2.2.12 — 2022-08-09
- 2.2.11 — 2022-08-09
- 2.2.9 — 2022-06-27
- 2.2.8 — 2022-06-16
- 2.2.7 — 2022-06-16
- 2.2.6 — 2022-06-16
- 2.2.5 — 2022-06-16
- … 27 more at https://npm.io/package/vuurrood-sockets/versions

## README

# Install

```shell
yarn add vuurrood-sockets@latest

# OR

npm install vuurrood-sockets@latest
```

# Basic usage

Initializing the socket server:

```typescript
import type { Server } from 'http'
import { initSocketServer } from 'vuurrood-sockets'

const startServer = (): Promise<Server> => new Promise(async (resolve) => {
  const server = app.listen(config.PORT, async () => {
    await initSocketServer(server, '*')
    resolve(server)
  })
})

startServer()
```

# Publishing to NPM
## IMPORTANT: Do not forget to upgrade (major, minor, patch) version in package.json

```shell
yarn publish
```

# Small examples

## Example 1
```typescript
interface IRoomClearInteraction {
  hostSocketId: string
  code: string
}

router.post('/clear-last-interaction', async (req, res, next) => {
  const body = req.body as IRoomClearInteraction

  if (!isSocketIdHost(body.hostSocketId, body.code)) {
    return res.status(403).json({})
  }

  const updatedRoom = removeInteractionFromRoom(body.code)

  if (!updatedRoom) {
    return res.sendStatus(404)
  }

  emitRoomUpdatedToHost(updatedRoom, 'roomUpdated')
  emitNewInteractionToRoom(updatedRoom, 'lastInteractionUpdated')

  res.sendStatus(201)
})
```

## Example 2
```typescript
interface IRoomCreateBody {
  hostSocketId: string
  code?: string
}

router.post('/create-room', async (req, res, next) => {
  try {
    const body = req.body as IRoomCreateBody
    let room

    if (body.code) {
      room = recoverRoom(body.hostSocketId, body.code)

      if (!isSocketIdHost(body.hostSocketId, body.code)) {
        return res.sendStatus(403)
      }

      emitRoomUpdatedToHost(room, 'roomUpdated')
      emitRoomUpdatedToAllParticipants(room, 'roomParticipantUpdated')
    } else {
      room = createRoom(body.hostSocketId)
      rooms.push(room)

      emitRoomUpdatedToHost(room, 'roomUpdated')
    }

    res.json({
      code: room.code
    })
  } catch (e) {
    res.status(500).json({
      error: e
    })
  }
})
```

# Functions

## Server
```typescript
const initSocketServer: (server: HttpServer, origin: string) => Promise<Server>
```

## Emitters
```typescript
// Emits Room to Host
const emitRoomUpdatedToHost: (room: Room, eventName: string) => void

// Emits lastInteraction to Room
const emitNewInteractionToRoom: (room: Room, eventName: string) => void

// Emits Room to all participants
const emitRoomUpdatedToAllParticipants: (room: Room, eventName: string) => void

// Emits Room to specific participant
const emitRoomUpdatedToParticipant: (participant: RoomParticipant, room: Room, eventName: string) => void

// Emits lastInteraction to specific participant
const emitInteractionToParticipant: (participant: RoomParticipant, eventName: string, interaction: RoomInteraction) => void

// Emits interaction to random participant
const emitInteractionToRandomParticipant: (room: Room, eventName: string, interaction: RoomInteraction) => void

// Emits to whole Room
const emitHostDisconnected: (room: Room, eventName: string) => void
const emitHostReconnected: (room: Room, eventName: string) => void
```

## Participants
```typescript
// Adds RoomParticipant to room if Room is open, returns Room if updated or undefined if Room is not found
const addParticipantToRoom: (code: string, participant: RoomParticipant) => Room | undefined

// Removes RoomParticipant from Room, returns Room if updated or undefined if Room is not found
const removeParticipantFromRoom: (code: string, participantId: string) => Room | undefined

// Gets specific RoomParticipant by participantId or undefined if RoomParticipant is not found
const getParticipantFromRoomById: (code: string, participantId: any) => RoomParticipant | undefined

// Adds a new interaction to RoomParticipant and returns Room if updated or undefined if Room is not found
const participantAddInteraction: (code: string, participantId: string, interaction: NewRoomParticipantInteraction) => Room | undefined

// Sets RoomParticipant to connected and returns Room if updated or undefined if Room is not found
const setParticipantConnected: (code: string, participantId: string, socketId: string) => Room | undefined

// Sets RoomParticipant to disconnected and returns Room if updated or undefined if Room is not found
const setParticipantDisconnected: (code: string, participantId: string) => Room | undefined

// Creates and returns a new RoomParticipant object 
const createRoomParticipant: (socketId: string, name?: string | undefined) => RoomParticipant
```

## Interactions
```typescript
// Creates and returns a new MESSAGE RoomInteraction object
const createMessageInteraction: (interactionData: string, interactionId?: string | undefined) => RoomInteraction

// Creates and returns a new SURVEY RoomInteraction object
const createSurveyInteraction: (interactionData: any, interactionId?: string | undefined) => RoomInteraction

// Creates and returns a new CHOICE RoomInteraction object
const createChoiceInteraction: (interactionData: any, interactionId?: string | undefined) => RoomInteraction

// Creates and returns a new RATING RoomInteraction object
const createRatingInteraction: (interactionData: any, interactionId?: string | undefined) => RoomInteraction

// Creates and returns a new RoomInteraction object
const createInteraction: (interactionType: InteractionType, interactionData: any, interactionId?: string | undefined) => RoomInteraction

// Adds RoomInteraction object to Room and returns Room if updated or undefined if Room is not found
const addLastInteractionToRoom: (code: string, interaction: RoomInteraction) => Room | undefined

// Removes RoomInteraction object from Room and returns Room if updated or undefined if Room is not found
const removeInteractionFromRoom: (code: string) => Room | undefined

// Gets all RoomInteractions from RoomParticipants by interactionId and returns RoomParticipantInteractions as array or undefined if no interactions with interactionId are found
const getInteractionsByInteractionId: (code: string, interactionId: string) => RoomParticipantInteraction[] | undefined
```

## Connecting / Disconnecting
```typescript
// Sets host to disconnected and returns Room if updated or undefined if Room is not found
const setHostDisconnected: (code: string) => Room | undefined

// Sets host to connected and returns Room if updated or undefined if Room is not found
const setHostConnected: (code: string, socketId: string) => Room | undefined

// If Host is disconnect, closes the Room and emits Room if updated to all RoomParticipants
// If RoomParticipant is disconnected, sets RoomParticipant to disconnected and emits Room if updated to Host 
const findDisconnectedUser: (socket: Socket) => void

// If Host connects/reconnects, opens the Room and emits Room if updated to all RoomParticipants
// If RoomParticipant connects/reconnects, sets RoomParticipant to connected and emits Room if updated to Host 
const findConnectedUser: (socket: Socket) => void
```

## Room
```typescript
// Generates unique code for Room and returns new code
const generateRoomCode: () => string

// Find and opens the Room, if no Room could be found a new Room is created with code
const recoverRoom: (hostSocketId: string, code: string, meta?: object | undefined, roomId?: string | undefined) => Room

// Creates and returns a new Room object
const createRoom: (hostSocketId: string, meta?: object | undefined, code?: string | undefined, roomId?: string | undefined) => Room

// Updates Room in global Room[] where all Rooms are stored in
// IMPORTANT: All functions updated a room do this automatically
const updateRoomInRoomArray: (room: Room) => void

// Returns the index of the Room in Room[]
const getRoomIndexByCode: (code: string) => number

// Returns the Room object or undefined if Room is not found
const getRoomByCode: (code: string) => Room | undefined

// Closes the Room and returns Room if updated or undefined if room is not found
const closeRoom: (code: string) => Room | undefined

// Opens the Room and returns Room if updated or undefined if room is not found
const openRoom: (code: string) => Room | undefined

// Finishes the Room and returns Room if updated or undefined if room is not found
const finishRoom: (code: string) => Room | undefined

// Resets the global Room[] back to empty Room[]
const resetRoomArray: () => void
```

# Types

## Room
```typescript
interface Room {
  id: string;
  code: string;
  meta: object;
  hostSocketId: string;
  isHostConnected: boolean;
  status: RoomStatus;
  participants: RoomParticipant[];
  lastInteraction?: RoomInteraction;
  hasVoting: boolean;
  finished?: Date;
  created: Date;
}

enum RoomStatus {
  CLOSED = "CLOSED",
  OPEN = "OPEN",
  FINISHED = "FINISHED"
}
```

## Participant
```typescript
interface RoomParticipant {
  id: string;
  name?: string;
  socketId: string;
  isConnected: boolean;
  interactions: RoomParticipantInteraction[];
}
```

## Interaction
```typescript
interface RoomParticipantInteraction {
  id: string;
  interactionId: string;
  interactionType: InteractionType;
  interactionData: any;
}

interface NewRoomParticipantInteraction {
  interactionId: string;
  interactionType: InteractionType;
  interactionData: any;
}

interface RoomInteraction {
  interactionId: string;
  interactionType: InteractionType;
  interactionData: any;
}

enum InteractionType {
  CHOICE = "CHOICE",
  SURVEY = "SURVEY",
  RATING = "RATING",
  MESSAGE = "MESSAGE"
}
```

---
_Source: https://npm.io/package/vuurrood-sockets · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
