1+ import { Schema , model , Document , Types , Model } from 'mongoose' ;
2+ import { Canvas } from './Canvas.js' ;
3+ import { CONFIG } from '../config.js' ;
4+
5+ export interface ILobby extends Document {
6+ name : string ;
7+ owner ?: Types . ObjectId ; // Links to your User schema
8+ canvas : Types . ObjectId ; // Links to Canvas schema
9+ allowedUsers : Types . ObjectId [ ] ;
10+ bannedUsers : Types . ObjectId [ ] ;
11+ createdAt : Date ;
12+ updatedAt : Date ;
13+ }
14+
15+ // Static method interface
16+ interface LobbyModel extends Model < ILobby > {
17+ createWithCanvas ( name : string , ownerId ?: string ) : Promise < ILobby > ;
18+ }
19+
20+ const lobbySchema = new Schema < ILobby > ( {
21+ name : {
22+ type : String ,
23+ required : true ,
24+ unique : true ,
25+ trim : true
26+ } ,
27+ owner : { type : Schema . Types . ObjectId , ref : 'User' } ,
28+ canvas : { type : Schema . Types . ObjectId , ref : 'Canvas' , required : true } ,
29+ allowedUsers : [ { type : Schema . Types . ObjectId , ref : 'User' } ] ,
30+ bannedUsers : [ { type : Schema . Types . ObjectId , ref : 'User' } ]
31+ } , { timestamps : true } ) ;
32+
33+ // --- FACTORY METHOD: Creates Lobby + Empty Canvas atomically ---
34+ lobbySchema . statics . createWithCanvas = async function ( name : string , ownerId ?: string ) {
35+ const lobbyId = new Types . ObjectId ( ) ;
36+ const canvasId = new Types . ObjectId ( ) ;
37+
38+ // Initialized to 0 (Transparent/White depending on palette)
39+ const emptyBuffer = Buffer . alloc ( CONFIG . CANVAS . WIDTH * CONFIG . CANVAS . HEIGHT , 0 ) ;
40+
41+ const canvas = new Canvas ( {
42+ _id : canvasId ,
43+ lobby : lobbyId ,
44+ width : CONFIG . CANVAS . WIDTH ,
45+ height : CONFIG . CANVAS . HEIGHT ,
46+ data : emptyBuffer
47+ } ) ;
48+
49+ const lobby = new this ( {
50+ _id : lobbyId ,
51+ name,
52+ owner : ownerId ? new Types . ObjectId ( ownerId ) : undefined ,
53+ canvas : canvasId
54+ } ) ;
55+
56+ // Save both
57+ await Promise . all ( [ canvas . save ( ) , lobby . save ( ) ] ) ;
58+ return lobby ;
59+ } ;
60+
61+ export const Lobby = model < ILobby , LobbyModel > ( 'Lobby' , lobbySchema ) ;
0 commit comments