@unispechq/unispec-express
v0.1.3
Published
Express adapter for UniSpec (REST route discovery and /unispec.json endpoint).
Readme
@unispechq/unispec-express
UniSpec adapter for Express applications.
- Automatically scans REST routes from
express.Application. - Detects GraphQL when using
express-graphql/Apollo-like middleware. - Collects WebSocket events for
socket.iowhen the helper is attached. - Exposes the UniSpec document at
/unispec.json.
Installation
pnpm add @unispechq/unispec-express expressTo use GraphQL or WebSocket, add the corresponding dependencies (see the example below).
Quick start (REST + GraphQL + WebSocket)
import http from "http";
import express from "express";
import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "graphql";
import { Server } from "socket.io";
import { mountUniSpecEndpoints, attachSocketIoToUniSpec } from "@unispechq/unispec-express";
const app = express();
// REST
app.get("/ping", (req, res) => {
res.json({ ok: true });
});
// GraphQL (express-graphql)
const schema = buildSchema(`
type Query {
hello: String
}
type Mutation {
setMessage(message: String!): String
}
type Subscription {
messageFeed: String
}
`);
const rootValue = {
hello: () => "Hello from GraphQL!",
setMessage: ({ message }: { message: string }) => message,
messageFeed: () => "Not implemented"
};
app.use(
"/graphql",
graphqlHTTP({
schema,
rootValue,
graphiql: true
})
);
// WebSocket (socket.io)
const server = http.createServer(app);
const io = new Server(server, { path: "/socket.io" });
attachSocketIoToUniSpec(io);
io.on("connection", (socket) => {
socket.on("chatMessage", () => {});
socket.on("typing", () => {});
});
// UniSpec
mountUniSpecEndpoints(app, {
service: {
id: "express-service",
name: "Express Service",
version: "1.0.0"
}
});
server.listen(3000, () => {
console.log("REST: http://localhost:3000/ping");
console.log("GraphQL: http://localhost:3000/graphql");
console.log("WebSocket: ws://localhost:3000/socket.io");
console.log("UniSpec doc: http://localhost:3000/unispec.json");
});What goes into UniSpec
In the /unispec.json response the adapter builds a single UniSpec document:
service.protocols.rest.paths— all REST routes.service.protocols.graphql— SDL and a basic list of operations from the GraphQL schema (if a GraphQL middleware is detected).service.protocols.websocket— channels inferred fromsocket.on("event")names (ifattachSocketIoToUniSpecwas called).
See a more complete example in the examples/express-basic directory.
