GraphQL strawberry的使用回顾和体会

GraphQL vs RESTful

简单来说GraphQL 比起 RESTful 集成额外一些功能

  1. 出入参校验、序列化 (简化后端编程)
  2. 自由可选的返回数据字段 (简化一些多余接口开发和沟通联调成本)

这些都是优点了。

开发效率在项目初期是很重要的,需要快速原型化。
但是后期稳定后,性能也很重要。

对比

RESTful + Pydantic

from sanic import Sanic, text
from pydantic import BaseModel
from typing import List

app = Sanic("simple")


class Simple(BaseModel):
    name: str
    age: int
    hobbies: List[str]


@app.post("/rest")
async def rest_test(request):
    Simple.model_validate(request.json)
    return text("ok")

k6测试代码
import { check } from 'k6';
import http from 'k6/http';

export default function () {

    let data = { "name": "Stephen Ling", "age": 28, "hobbies": ["coding", "coffee"] }

    const res = http.post('http://localhost:9090/rest', JSON.stringify(data), {
        headers: { 'Content-Type': 'application/json' },
    });
    check(res, {
        'is status 200': (r) => r.status === 200,
    });
}

在这里插入图片描述

GraphQL(strawberry)

k6测试代码
import { check } from 'k6';
import http from 'k6/http';

export default function () {

    let data = {
        "query": "mutation {\n  resolveGraphql(name: \"Stephen Ling\", age: 28, hobbies: [\"coding\", \"coffee\"])\n}"
    }

    const res = http.post('http://localhost:9090/graphql', JSON.stringify(data), {
        headers: { 'Content-Type': 'application/json' },
    });
    check(res, {
        'is status 200': (r) => r.status === 200,
    });
}

默认情况
import strawberry
from strawberry.sanic.views import GraphQLView
from sanic import Sanic, text

from pydantic import BaseModel
from typing import List

app = Sanic("simple")


@strawberry.type
class Mutation:
    @strawberry.mutation
    async def resolve_graphql(self, name: str, age: int, hobbies: List[str]) -> str:
        return "ok"


@strawberry.type
class Query:
    @strawberry.field
    async def nothing(self) -> None:
        ...


app.add_route(
    GraphQLView.as_view(
        schema=strawberry.Schema(
            query=Query,
            mutation=Mutation,
        ),
    ),
    "/graphql",
)

在这里插入图片描述

加上缓存
...
from strawberry.extensions import ParserCache, ValidationCache

...
app.add_route(
    GraphQLView.as_view(
        schema=strawberry.Schema(
            query=Query,
            mutation=Mutation,
            extensions=[ParserCache(), ValidationCache()],
        ),
    ),
    "/graphql",
)

在这里插入图片描述

体会

  1. graphql 适合减轻前后端联调的沟通成本。谁错谁对一目了然。
  2. 选择实现库之前,衡量一下性能代价是否能接受。
  3. 实现库之间尽可能横向对比一下。
  4. 在可以忍受的性能差距下,我会选择开发效率,毕竟每个代码的生命周期是有限的,没有必要死磕。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值