-
Notifications
You must be signed in to change notification settings - Fork 25
Introduce HttpServer (and begin deprecating HttpPlugin) #433
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
heyitsaamir
wants to merge
33
commits into
aamirj/simlifyHttp
Choose a base branch
from
httpAdapter
base: aamirj/simlifyHttp
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
3e6af08
Configurable Http Plugin
heyitsaamir 8ab16d1
Fix lint
heyitsaamir 4f53f18
Remove configurable-http-plugin for HttpServer.
heyitsaamir 660e392
Use Adapter
heyitsaamir 38972de
Fix
heyitsaamir f5230f5
Jwt Validation
heyitsaamir b57ffe8
HttpServer
heyitsaamir 7acbcbc
Logger
heyitsaamir ff52956
Fix
heyitsaamir fee1672
Fix tests
heyitsaamir 235c202
Update
heyitsaamir a66ba33
Separate activity sending from HTTP transport layer
heyitsaamir 15855e3
Revert
heyitsaamir d6582a9
Revert
heyitsaamir 6795d82
Configurable Http Plugin
heyitsaamir 65d71ab
Fix lint
heyitsaamir 8555f2b
Remove configurable-http-plugin for HttpServer.
heyitsaamir 638f876
Use Adapter
heyitsaamir 3d2ec46
HttpServer
heyitsaamir 38c274f
Remove paths
heyitsaamir 9ada3a0
Fix examples
heyitsaamir df71c55
Fix readme
heyitsaamir a4c63e2
Fix
heyitsaamir fec351f
package-lock.json
heyitsaamir 0f2c0df
nextjs -> fastify
heyitsaamir 6df7ce3
fix ci
heyitsaamir 8556c4a
fix bot builder
heyitsaamir 42c7614
Fix tests
heyitsaamir df6cf81
Fix
heyitsaamir 1d3651b
Add build essential
heyitsaamir e6e08a0
Revert express
heyitsaamir b5139d0
add test for tab
heyitsaamir 95d91e9
fix tests
heyitsaamir File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| PORT=3978 | ||
| CLIENT_ID=your-client-id | ||
| CLIENT_SECRET=your-client-secret |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # HTTP Adapter Examples | ||
|
|
||
| This example shows how to integrate teams.ts with different HTTP frameworks using custom adapters. | ||
|
|
||
| ## What's an Adapter? | ||
|
|
||
| An adapter bridges your HTTP framework with teams.ts. You create your server, pass it to the adapter, and teams.ts adds the `/api/messages` bot endpoint to your existing app. | ||
|
|
||
| ## Examples | ||
|
|
||
| - **[express/](./express/)** - Hook your own Express server with the built-in Express adapter | ||
| - **[hono/](./hono/)** - Build a custom adapter and manage the lifecycle yourself | ||
| - **[fastify/](./fastify/)** - Build a custom adapter and let App manage its lifecycle | ||
|
|
||
| ## Running | ||
|
|
||
| ```bash | ||
| npm install | ||
| cp .env.example .env | ||
|
|
||
| # Run an example | ||
| npm run dev:express | ||
| npm run dev:hono | ||
| npm run dev:fastify | ||
| ``` | ||
|
|
||
| All examples start on `http://localhost:3978` with `/api/messages` as the bot endpoint. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import 'dotenv/config'; | ||
| import { app, httpServer } from './teams-app'; | ||
|
|
||
| const port = parseInt(process.env.PORT || '3978', 10); | ||
|
|
||
| async function main() { | ||
| console.log('Starting Express server with Teams bot integration...\n'); | ||
|
|
||
| // Initialize teams.ts app - this adds /api/messages to your Express app | ||
| await app.initialize(); | ||
|
|
||
| // Start your Express server | ||
| await new Promise<void>((resolve, reject) => { | ||
| httpServer.listen(port, () => resolve()); | ||
| httpServer.once('error', reject); | ||
| }); | ||
|
|
||
| console.log(`✓ Server ready on http://localhost:${port}`); | ||
| console.log(`\nYour Express routes:`); | ||
| console.log(` GET / - Homepage`); | ||
| console.log(` GET /health - Health check`); | ||
| console.log(` GET /api/users - Users API`); | ||
| console.log(` POST /api/messages - Teams bot endpoint (added by teams.ts)`); | ||
| console.log(`\nOpen http://localhost:${port} in your browser!`); | ||
| } | ||
|
|
||
| main().catch((err) => { | ||
| console.error('Failed to start:', err); | ||
| process.exit(1); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import http from 'http'; | ||
| import express from 'express'; | ||
| import { App, ExpressAdapter } from '@microsoft/teams.apps'; | ||
|
|
||
| // 1. Create your existing Express app with routes | ||
| export const expressApp = express(); | ||
| export const httpServer = http.createServer(expressApp); | ||
|
|
||
| // Add your custom routes | ||
| expressApp.get('/health', (_req, res) => { | ||
| res.json({ status: 'healthy', timestamp: new Date().toISOString() }); | ||
| }); | ||
|
|
||
| expressApp.get('/api/users', (_req, res) => { | ||
| res.json({ | ||
| users: [ | ||
| { id: 1, name: 'Alice' }, | ||
| { id: 2, name: 'Bob' } | ||
| ] | ||
| }); | ||
| }); | ||
|
|
||
| expressApp.get('/', (_req, res) => { | ||
| res.send(` | ||
| <html> | ||
| <body> | ||
| <h1>Express + teams.ts</h1> | ||
| <p>Your Express server is running with a Teams bot!</p> | ||
| <ul> | ||
| <li><a href="/health">Health Check</a></li> | ||
| <li><a href="/api/users">API: Users</a></li> | ||
| <li><strong>/api/messages</strong> - Teams bot endpoint</li> | ||
| </ul> | ||
| </body> | ||
| </html> | ||
| `); | ||
| }); | ||
|
|
||
| // 2. Create Express adapter with your existing server | ||
| export const adapter = new ExpressAdapter(httpServer); | ||
|
|
||
| // 3. Create teams.ts app with the adapter | ||
| export const app = new App({ | ||
| httpAdapter: adapter | ||
| }); | ||
|
|
||
| // 4. Handle incoming messages | ||
| app.on('message', async ({ send, activity }) => { | ||
| await send(`Echo from Express server: ${activity.text}`); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import fastify, { FastifyInstance } from 'fastify'; | ||
| import { IHttpAdapter, IRouteConfig } from '@microsoft/teams.apps/dist/http/adapter'; | ||
|
|
||
| /** | ||
| * Fastify adapter for HttpServer | ||
| * | ||
| * Handles Fastify-specific HTTP framework concerns: | ||
| * - Fastify app creation and initialization | ||
| * - Route registration via Fastify routing | ||
| * - Request/response data extraction and sending | ||
| * - Server lifecycle management | ||
| * | ||
| * Usage: | ||
| * const adapter = new FastifyAdapter(); | ||
| * const app = new App({ httpAdapter: adapter }); | ||
| * await app.initialize(); | ||
| * await app.start(3978); | ||
| */ | ||
| export class FastifyAdapter implements IHttpAdapter { | ||
| protected fastify: FastifyInstance; | ||
| protected isUserProvidedInstance: boolean; | ||
|
|
||
| constructor(instance?: FastifyInstance) { | ||
| this.isUserProvidedInstance = !!instance; | ||
| this.fastify = instance || fastify({ logger: true }); | ||
| } | ||
|
|
||
| /** | ||
| * Get the Fastify instance for adding custom routes/plugins | ||
| */ | ||
| get instance(): FastifyInstance { | ||
| return this.fastify; | ||
| } | ||
|
|
||
| /** | ||
| * Register a route with Fastify | ||
| */ | ||
| registerRouteHandler(config: IRouteConfig): void { | ||
| const { path, handler } = config; | ||
|
|
||
| // Register with Fastify | ||
| this.fastify.route({ | ||
| method: 'POST', | ||
| url: path, | ||
| handler: async (request, reply) => { | ||
| try { | ||
| // Provide helpers to the handler | ||
| await handler({ | ||
| extractRequestData: () => ({ | ||
| body: request.body as any, | ||
| headers: request.headers as Record<string, string> | ||
| }), | ||
| sendResponse: (response) => { | ||
| reply.status(response.status).send(response.body); | ||
| } | ||
| }); | ||
| } catch (err) { | ||
| reply.status(500).send({ error: 'Internal server error' }); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Initialize the adapter | ||
| * No initialization needed - Fastify will call ready() automatically when listen() is called | ||
| */ | ||
| async initialize(): Promise<void> { | ||
| // No initialization needed for Fastify | ||
| // Routes must be registered before calling listen() | ||
| // Fastify will automatically call ready() when listen() is invoked | ||
| } | ||
|
|
||
| /** | ||
| * Start the server | ||
| * Throws if instance was user-provided | ||
| */ | ||
| async start(port: number): Promise<void> { | ||
| if (this.isUserProvidedInstance) { | ||
| throw new Error( | ||
| 'Cannot call start() when Fastify instance was provided by user. ' + | ||
| 'User should call fastify.listen() directly.' | ||
| ); | ||
| } | ||
|
|
||
| await this.fastify.listen({ port, }); | ||
| } | ||
|
|
||
| /** | ||
| * Stop the server | ||
| */ | ||
| async stop(): Promise<void> { | ||
| if (!this.isUserProvidedInstance) { | ||
| await this.fastify.close(); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import 'dotenv/config'; | ||
| import { app } from './teams-app'; | ||
|
|
||
| const port = parseInt(process.env.PORT || '3978', 10); | ||
|
|
||
| async function main() { | ||
| console.log('Starting Fastify server with Teams bot integration...\n'); | ||
|
|
||
| // In this case, we're choosing to use a Fastify server to run the app | ||
| // app.start() will initialize the app and start the Fastify server | ||
| // | ||
| // Alternatively, we could have used app.initialize() and then started | ||
| // the Fastify server separately with adapter.instance.listen() | ||
| await app.start(port); | ||
|
|
||
| console.log(`✓ Server ready on http://localhost:${port}`); | ||
| console.log(`\nYour Fastify routes:`); | ||
| console.log(` GET / - Homepage`); | ||
| console.log(` GET /health - Health check`); | ||
| console.log(` GET /api/users - Users API`); | ||
| console.log(` POST /api/messages - Teams bot endpoint (added by teams.ts)`); | ||
| console.log(`\nOpen http://localhost:${port} in your browser!`); | ||
| } | ||
|
|
||
| main().catch((err) => { | ||
| console.error('Failed to start:', err); | ||
| process.exit(1); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import { App } from '@microsoft/teams.apps'; | ||
| import { FastifyAdapter } from './fastify-adapter'; | ||
|
|
||
| // 1. Create Fastify adapter | ||
| export const adapter = new FastifyAdapter(); | ||
|
|
||
| // Get the Fastify instance to add custom routes | ||
| const fastify = adapter.instance; | ||
|
|
||
| // 2. Add your custom routes | ||
| fastify.get('/health', async (_request, reply) => { | ||
| return reply.send({ status: 'healthy', timestamp: new Date().toISOString() }); | ||
| }); | ||
|
|
||
| fastify.get('/api/users', async (_request, reply) => { | ||
| return reply.send({ | ||
| users: [ | ||
| { id: 1, name: 'Alice' }, | ||
| { id: 2, name: 'Bob' } | ||
| ] | ||
| }); | ||
| }); | ||
|
|
||
| fastify.get('/', async (_request, reply) => { | ||
| return reply.type('text/html').send(` | ||
| <html> | ||
| <body> | ||
| <h1>Fastify + teams.ts</h1> | ||
| <p>Your Fastify server is running with a Teams bot!</p> | ||
| <ul> | ||
| <li><a href="/health">Health Check</a></li> | ||
| <li><a href="/api/users">API: Users</a></li> | ||
| <li><strong>/api/messages</strong> - Teams bot endpoint</li> | ||
| </ul> | ||
| </body> | ||
| </html> | ||
| `); | ||
| }); | ||
|
|
||
| // 3. Create teams.ts app with the adapter | ||
| export const app = new App({ | ||
| httpAdapter: adapter, | ||
| }); | ||
|
|
||
| // 4. Handle incoming messages | ||
| app.on('message', async ({ send, activity }) => { | ||
| await send(`Echo from Fastify server: ${activity.text}`); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { Hono, Context } from 'hono'; | ||
| import { IHttpAdapter, IRouteConfig } from '@microsoft/teams.apps/dist/http/adapter'; | ||
|
|
||
| /** | ||
| * Hono adapter for HttpServer | ||
| * | ||
| * Wraps an existing Hono app to add Teams bot routes. | ||
| * Server lifecycle (start/stop) is managed by the user externally. | ||
| * | ||
| * Usage: | ||
| * const hono = new Hono(); | ||
| * const app = new App({ httpAdapter: new HonoAdapter(hono) }); | ||
| * await app.initialize(); | ||
| * // Start your Hono server separately with serve() or @hono/node-server | ||
| */ | ||
| export class HonoAdapter implements IHttpAdapter { | ||
| protected hono: Hono; | ||
|
|
||
| /** | ||
| * Create adapter with your existing Hono app | ||
| * @param hono Your Hono app with your custom routes | ||
| */ | ||
| constructor(hono: Hono) { | ||
| this.hono = hono; | ||
| } | ||
|
|
||
| /** | ||
| * Register a POST route handler with Hono | ||
| * All routes are POST-only (Teams bot protocol uses POST) | ||
| */ | ||
| registerRouteHandler(config: IRouteConfig): void { | ||
| const { path, handler } = config; | ||
|
|
||
| // Convert handler to Hono handler signature | ||
| const honoHandler = async (c: Context) => { | ||
| try { | ||
| // Parse JSON body | ||
| const body = await c.req.json().catch(() => ({})); | ||
| const headers = Object.fromEntries(c.req.raw.headers.entries()); | ||
|
|
||
| let responseData: { status: number; body: any } | undefined; | ||
|
|
||
| // Provide helpers to the handler | ||
| await handler({ | ||
| extractRequestData: () => ({ | ||
| body, | ||
| headers | ||
| }), | ||
| sendResponse: (response) => { | ||
| responseData = response; | ||
| } | ||
| }); | ||
|
|
||
| // Send the response | ||
| if (responseData) { | ||
| return c.json(responseData.body, responseData.status as any); | ||
| } else { | ||
| return c.json({ error: 'No response provided' }, 500); | ||
| } | ||
| } catch (err) { | ||
| console.error('Hono handler error:', err); | ||
| return c.json({ error: 'Internal server error' }, 500); | ||
| } | ||
| }; | ||
|
|
||
| // Register as POST route | ||
| this.hono.post(path, honoHandler); | ||
| } | ||
|
|
||
| /** | ||
| * Serve static files from a directory | ||
| * Note: For production, consider using Hono's built-in static middleware | ||
| * or a CDN for better performance | ||
| */ | ||
| serveStatic(path: string, directory: string): void { | ||
| // Hono's static file serving | ||
| this.hono.get(`${path}/*`, async (c) => { | ||
| const filePath = c.req.path.replace(path, directory); | ||
| try { | ||
| const fs = await import('fs/promises'); | ||
| const content = await fs.readFile(filePath); | ||
| return c.body(content); | ||
| } catch { | ||
| return c.notFound(); | ||
| } | ||
| }); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is cute, should we do the same in other languages/samples?