@social.dev/server-sdk
v0.0.1-alpha.75
Published
Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.
Readme
@social.dev/server-sdk
Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.
Overview
The @social.dev/server-sdk package provides:
- 🏗️ NestJS Framework - Built on top of NestJS 11 for enterprise-grade applications
- 🔐 Authentication System - Multiple auth methods including OIDC, JWT, and cookie-based sessions
- 💾 Database Integration - TypeORM with PostgreSQL support and migration tools
- 🔌 Plugin Architecture - Extensible plugin system for custom functionality
- 💬 Chat System - Real-time messaging with conversation management
- 👥 Community Features - Sub-communities with member management
- 📝 Post Management - Content creation and interaction system
- 🔔 Notifications - Push notification support with device management
- 📁 File Storage - S3-compatible file storage integration
- 📊 API Documentation - Auto-generated Swagger/OpenAPI documentation
- 🌐 Multi-Network Support - Domain-based network isolation
Installation
# Using pnpm (recommended)
pnpm add @social.dev/server-sdk
# Using npm
npm install @social.dev/server-sdk
# Using yarn
yarn add @social.dev/server-sdkPrerequisites
- Node.js 18 or higher
- PostgreSQL 14 or higher
- Redis (optional, for caching)
- S3-compatible storage (optional, for file uploads)
Quick Start
Basic Setup
Create a new file index.ts in your server application:
import { bootstrap } from '@social.dev/server-sdk/bootstrap';
// Initialize the server with minimal configuration
bootstrap({
auth: {
methods: ['password'], // Enable password authentication
},
});Advanced Setup with OIDC and Plugins
import { bootstrap } from '@social.dev/server-sdk/bootstrap';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import SocialDevAiPlugin from '@social.dev/plugin-ai';
// Register plugins before bootstrap
PluginFactory.addPlugin(
SocialDevAiPlugin.forRoot({
userIds: [3], // User IDs that can access AI features
}),
);
// Bootstrap the server with comprehensive configuration
bootstrap({
auth: {
methods: [AuthMethodEnum.Oidc, AuthMethodEnum.Password],
oidc: {
providers: [
{
id: 'keycloak',
name: 'Company Keycloak',
issuer: 'https://keycloak.example.com/auth/realms/company',
clientId: 'social-dev-app',
clientSecret: process.env.OIDC_CLIENT_SECRET,
},
],
},
},
network: {
domainAliasMap: {
localhost: 1,
'dev.example.com': 2,
'staging.example.com': 3,
},
},
});Configuration
Environment Variables
Create a .env file in your project root:
# Server Configuration
SOCIAL_DEV_SERVER_PORT=3000
NODE_ENV=development
# Database Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=socialdev
POSTGRES_PASSWORD=yourpassword
POSTGRES_DB=socialdev_db
# Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d
# OIDC Configuration (optional)
OIDC_CLIENT_SECRET=your-oidc-secret
# S3 Storage (optional)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
S3_BUCKET_NAME=socialdev-uploads
# Push Notifications (optional)
FCM_SERVER_KEY=your-fcm-server-key
APNS_KEY_ID=your-apns-key-id
APNS_TEAM_ID=your-apns-team-idBootstrap Configuration Options
interface BootstrapConfig {
auth?: {
// Available authentication methods
methods: AuthMethodEnum[];
// OIDC provider configuration
oidc?: {
providers: OidcProvider[];
};
// JWT configuration
jwt?: {
secret?: string;
expiresIn?: string;
};
};
network?: {
// Map domains to network IDs for multi-tenant support
domainAliasMap: { [domain: string]: number };
};
database?: {
// Override default database configuration
host?: string;
port?: number;
username?: string;
password?: string;
database?: string;
synchronize?: boolean; // Auto-sync schema (dev only!)
};
storage?: {
// S3 configuration
accessKeyId?: string;
secretAccessKey?: string;
region?: string;
bucket?: string;
};
}Core Modules
Authentication Module
The SDK supports multiple authentication methods:
// Available authentication methods
enum AuthMethodEnum {
Password = 'password',
Oidc = 'oidc',
Magic = 'magic', // Magic link via email
}
// OIDC Provider configuration
interface OidcProvider {
id: string; // Unique identifier
name: string; // Display name
issuer: string; // OIDC issuer URL
clientId: string; // OAuth client ID
clientSecret: string; // OAuth client secret
scope?: string; // OAuth scopes (default: 'openid profile email')
}User Module
User management with profiles and authentication:
// User entity structure
interface User {
id: number;
username: string;
email: string;
name?: string;
bio?: string;
avatar?: string;
verified: boolean;
createdAt: Date;
updatedAt: Date;
}Post Module
Content creation and management:
// Post entity structure
interface Post {
id: number;
content: string;
authorId: number;
parentId?: number; // For replies
attachments?: MediaAsset[];
likes: number;
comments: number;
shares: number;
createdAt: Date;
updatedAt: Date;
}Chat Module
Real-time messaging system:
// Conversation management
interface Conversation {
id: number;
participants: User[];
lastMessage?: Message;
unreadCount: number;
createdAt: Date;
updatedAt: Date;
}
// Message structure
interface Message {
id: number;
conversationId: number;
senderId: number;
content: string;
attachments?: MediaAsset[];
readBy: number[];
createdAt: Date;
}Community Module
Sub-communities (subs) management:
// Sub entity structure
interface Sub {
id: number;
name: string;
description?: string;
avatar?: string;
banner?: string;
memberCount: number;
postCount: number;
createdAt: Date;
}
// Member management
interface SubMember {
subId: number;
userId: number;
role: 'owner' | 'moderator' | 'member';
joinedAt: Date;
}Notification Module
Push notification management:
// Device registration
interface NotificationDevice {
id: number;
userId: number;
token: string;
platform: 'ios' | 'android' | 'web';
active: boolean;
}
// Notification sending
interface Notification {
userId: number;
title: string;
body: string;
data?: Record<string, any>;
priority?: 'high' | 'normal';
}Plugin System
The SDK supports a powerful plugin architecture for extending functionality:
Creating a Custom Plugin
// plugins/my-plugin/index.ts
import { Injectable, Module } from '@nestjs/common';
import { PluginInterface } from '@social.dev/server-sdk/core/plugin/plugin.interface';
@Injectable()
class MyPluginService {
async processContent(content: string): Promise<string> {
// Your plugin logic here
return content.toUpperCase();
}
}
@Module({
providers: [MyPluginService],
exports: [MyPluginService],
})
export class MyPlugin implements PluginInterface {
static forRoot(options?: { enabled?: boolean }) {
return {
module: MyPlugin,
providers: [
{
provide: 'MY_PLUGIN_OPTIONS',
useValue: options || {},
},
],
};
}
}Registering Plugins
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import { MyPlugin } from './plugins/my-plugin';
// Register plugin before bootstrap
PluginFactory.addPlugin(
MyPlugin.forRoot({
enabled: true,
}),
);
// Then bootstrap the server
bootstrap({
/* ... */
});Database Migrations
Generating Migrations
# Build the SDK first
pnpm build
# Generate a new migration based on entity changes
npx typeorm migration:generate \
-d ./dist/manage-db.js \
./src/migrations/NewMigrationRunning Migrations
# Run all pending migrations
npx typeorm migration:run \
-d ./node_modules/@social.dev/server-sdk/dist/manage-db.js
# Revert the last migration
npx typeorm migration:revert \
-d ./node_modules/@social.dev/server-sdk/dist/manage-db.jsCreating Custom Migrations
// migrations/1234567890-CustomMigration.ts
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class CustomMigration1234567890 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'custom_table',
columns: [
{
name: 'id',
type: 'int',
isPrimary: true,
isGenerated: true,
generationStrategy: 'increment',
},
{
name: 'name',
type: 'varchar',
},
],
}),
true,
);
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('custom_table');
}
}API Documentation
The SDK automatically generates Swagger/OpenAPI documentation:
# Start your server
pnpm dev
# Access the documentation
open http://localhost:3000/schemaCustom API Endpoints
You can add custom endpoints by creating NestJS controllers:
// src/custom/custom.controller.ts
import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@social.dev/server-sdk/auth/auth.guard';
@ApiTags('custom')
@Controller('custom')
export class CustomController {
@Get('public')
getPublicData() {
return { message: 'This is public' };
}
@Post('protected')
@UseGuards(AuthGuard)
@ApiBearerAuth()
createProtectedResource(@Body() data: any) {
return { success: true, data };
}
}
// Register in a module
@Module({
controllers: [CustomController],
})
export class CustomModule {}Development Scripts
# Install dependencies
pnpm install
# Development mode with hot reload
pnpm dev
# Build for production
pnpm build
# Start production server
pnpm start:prod
# Run tests
pnpm test
# Run tests with coverage
pnpm test:cov
# Lint code
pnpm lint
# Format code
pnpm formatProduction Deployment
Using PM2
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'social-dev-server',
script: './dist/index.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
SOCIAL_DEV_SERVER_PORT: 3000,
},
},
],
};# Build and start with PM2
pnpm build
pm2 start ecosystem.config.jsUsing Docker
# Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json pnpm-lock.yaml ./
RUN npm install -g pnpm
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
EXPOSE 3000
CMD ["node", "dist/index.js"]Using Vercel
// vercel.json
{
"version": 2,
"builds": [
{
"src": "api/index.ts",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/api"
}
]
}// api/index.ts
import { bootstrap } from '@social.dev/server-sdk/bootstrap';
export default async function handler(req, res) {
const app = await bootstrap({
// Your configuration
});
return app.getHttpAdapter().getInstance()(req, res);
}Multi-Network Support
The SDK supports running multiple isolated networks on a single server instance:
bootstrap({
network: {
domainAliasMap: {
'network1.example.com': 1,
'network2.example.com': 2,
'api.company.com': 3,
},
},
});
// Each domain will have isolated:
// - Users and authentication
// - Posts and content
// - Communities
// - Chat conversations
// - NotificationsSecurity Best Practices
- Environment Variables: Never commit
.envfiles to version control - Database: Always disable
synchronizein production - CORS: Configure allowed origins in production
- Rate Limiting: Implement rate limiting for API endpoints
- Input Validation: Use DTOs with class-validator for all inputs
- Authentication: Use strong JWT secrets and appropriate expiration times
- HTTPS: Always use HTTPS in production
TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import type {
User,
Post,
Sub,
Message,
Conversation,
AuthMethodEnum,
OidcProvider,
Configs,
} from '@social.dev/server-sdk';Examples
Check out the apps/server directory for a complete implementation example using the SDK.
Example Server Implementation
// apps/server/index.ts
import SocialDevAiPlugin from '@social.dev/plugin-ai';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
// Initialize plugins
PluginFactory.addPlugin(
SocialDevAiPlugin.forRoot({
userIds: [3],
}),
);
// Initialize the server
import('@social.dev/server-sdk/bootstrap').then(({ bootstrap }) => {
bootstrap({
auth: {
methods: [AuthMethodEnum.Oidc],
oidc: {
providers: [
{
id: 'minds-inc',
name: 'Minds Keycloak',
issuer: 'https://keycloak.minds.com/auth/realms/minds-inc',
clientId: 'demo-social-dev',
clientSecret: process.env.SOCIAL_DEV_OIDC_SECRET,
},
],
},
},
network: {
domainAliasMap: {
localhost: 2,
},
},
});
});Troubleshooting
Common Issues
Database Connection Failed
- Check PostgreSQL is running
- Verify database credentials in
.env - Ensure database exists
Port Already in Use
- Change
SOCIAL_DEV_SERVER_PORTin.env - Kill existing process:
lsof -i :3000
- Change
Migration Errors
- Build the SDK first:
pnpm build - Check database permissions
- Review migration SQL for conflicts
- Build the SDK first:
OIDC Authentication Failed
- Verify issuer URL is accessible
- Check client ID and secret
- Ensure redirect URIs are configured
Contributing
Contributions are welcome! Please read our contributing guidelines before submitting PRs.
License
MIT
