Node.js 中使用 GraphQL、WebSockets 和 Serverless

person 有无相生    watch_later 2024-08-10 10:26:05
visibility 150    class GraphQL,WebSockets,Serverless    bookmark 专栏

在 Node.js 中使用 GraphQL、WebSockets 和 Serverless

1. GraphQL

GraphQL 是一种用于 API 的查询语言,允许客户端只请求所需的数据。相比传统的 REST API,GraphQL 提供了更灵活和高效的数据获取方式。

1.1 安装和配置

安装相关库

npm install graphql express-graphql

创建 GraphQL Schema 和 Resolver

示例:schema.js

const { GraphQLObjectType, GraphQLSchema, GraphQLString } = require('graphql');

const HelloType = new GraphQLObjectType({
    name: 'Hello',
    fields: {
        message: { type: GraphQLString }
    }
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        hello: {
            type: HelloType,
            resolve() {
                return { message: 'Hello, world!' };
            }
        }
    }
});

const Mutation = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        updateMessage: {
            type: HelloType,
            args: {
                message: { type: GraphQLString }
            },
            resolve(parent, args) {
                return { message: args.message };
            }
        }
    }
});

module.exports = new GraphQLSchema({
    query: RootQuery,
    mutation: Mutation
});

设置 GraphQL 服务器

示例:index.js

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');

const app = express();

app.use('/graphql', graphqlHTTP({
    schema,
    graphiql: true // 开启 GraphiQL UI
}));

app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));

GraphQL 查询示例

query {
    hello {
        message
    }
}

mutation {
    updateMessage(message: "Hello, GraphQL!") {
        message
    }
}

2. WebSockets

WebSocket 是一种在客户端和服务器之间建立持久连接的协议,允许实时双向通信。

2.1 安装和配置

安装 WebSocket 库

npm install ws

创建 WebSocket 服务器

示例:websocket-server.js

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
    console.log('New client connected');

    ws.on('message', message => {
        console.log('Received:', message);
        ws.send(`Echo: ${message}`);
    });

    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server running on ws://localhost:8080');

客户端 WebSocket 示例

<!DOCTYPE html>
<html>
<body>
    <script>
        const ws = new WebSocket('ws://localhost:8080');

        ws.onopen = () => {
            console.log('WebSocket connection opened');
            ws.send('Hello, WebSocket!');
        };

        ws.onmessage = event => {
            console.log('Message from server:', event.data);
        };

        ws.onclose = () => {
            console.log('WebSocket connection closed');
        };
    </script>
</body>
</html>

3. Serverless

Serverless 是一种云计算模型,允许开发人员构建和运行应用程序而无需管理服务器。在 Node.js 中,可以使用 AWS Lambda、Azure Functions 等来实现 Serverless 架构。

3.1 AWS Lambda

安装 AWS SDK 和 AWS CLI

npm install aws-sdk

创建 Lambda 函数

示例:index.js

exports.handler = async (event) => {
    console.log('Event:', event);
  
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
  
    return response;
};

部署 Lambda 函数

  1. 打包 Lambda 函数
zip -r function.zip index.js
  1. 创建 Lambda 函数
aws lambda create-function --function-name my-function \
    --runtime nodejs14.x \
    --role arn:aws:iam::123456789012:role/service-role/lambda-role \
    --handler index.handler \
    --zip-file fileb://function.zip
  1. 测试 Lambda 函数
aws lambda invoke --function-name my-function output.txt
3.2 Azure Functions

创建 Azure Function

  1. 安装 Azure CLI 和 Azure Functions Core Tools
  2. 初始化 Azure Functions 项目
func init myFunctionApp --javascript
cd myFunctionApp
  1. 创建 HTTP 触发器函数
func new --name HttpTrigger --template "HTTP trigger" --authlevel "anonymous"

示例:HttpTrigger/index.js

module.exports = async function (context, req) {
    context.res = {
        body: "Hello from Azure Functions!"
    };
};

部署到 Azure

az login
az account set --subscription <subscription-id>
func azure functionapp publish <function-app-name>

总结

  • GraphQL:用于构建灵活的 API,支持动态查询和变更。
  • WebSockets:用于实现实时双向通信。
  • Serverless:通过云服务实现无服务器架构,降低运维成本。

通过这些技术,你可以构建功能强大、灵活、实时响应的 Node.js 应用程序。

评论区
评论列表
menu