亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

apollo 服務器 + 續集錯誤非空字段

apollo 服務器 + 續集錯誤非空字段

森欄 2023-09-28 09:50:29
我正在運行一個apollo 服務器,并將sequelize 作為postgres 數據庫的orm。這是架構:    type Tag {        id: ID!        name: String!    }    type Service {        id: ID!        name: String!        slug: String!        tags: [Tag!]!    }解析器:        findServicesByTag: async(_, { tag }, { models }) => {            const res = await models.Service.findAll({                where: {                    '$Tags.name$': tag                }                ,include: [                    {                        model: models.Tag,                        as: 'Tags'                    }                ]            })            console.log(res)            return res        }但是當執行這個查詢時query {  findServicesByTag(tag: "restaurant")  {    id name slug    tags {      name    }  }}我收到消息“無法為不可為空的字段 Service.id 返回 null”。console.log 指令打印此數據:[ Service {    dataValues: { id: 1, name: 'Restaurant X', Tags: [Array] },    _previousDataValues: { id: 1, name: 'Restaurant X', Tags: [Array] },    _changed: Set {},    _options:     { isNewRecord: false,       _schema: null,       _schemaDelimiter: '',       include: [Array],       includeNames: [Array],       includeMap: [Object],       includeValidated: true,       attributes: [Array],       raw: true },    isNewRecord: false,    Tags: [ [Tag] ] },  Service {    dataValues: { id: 2, name: 'Restaurant Y', Tags: [Array] },    _previousDataValues: { id: 2, name: 'Restaurant Y', Tags: [Array] },    _changed: Set {},    _options:     { isNewRecord: false,       _schema: null,       _schemaDelimiter: '',       include: [Array],       includeNames: [Array],       includeMap: [Object],       includeValidated: true,       attributes: [Array],       raw: true },    isNewRecord: false,    Tags: [ [Tag] ] } ]看起來 apollo 無法處理此數據,它不會查詢后續標簽實體。
查看完整描述

1 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

您應該使用instance.get方法來獲取dataValues。

模型實例使用屬性的概念進行操作dataValues,屬性存儲由實例表示的實際值。

然后,您需要定義alias: 'tags'模型關聯,因為 graphql 類型對象 -service具有tags字段。確保它們映射正確。

"sequelize": "^5.21.3"使用和 的工作示例"apollo-server": "^2.19.0"。

model.ts

import { sequelize } from '../../db';

import { Model, DataTypes } from 'sequelize';


class Service extends Model {}

Service.init(

? {

? ? id: {

? ? ? primaryKey: true,

? ? ? type: DataTypes.INTEGER,

? ? ? autoIncrement: true,

? ? ? allowNull: false,

? ? },

? ? name: DataTypes.STRING,

? ? slug: DataTypes.STRING,

? },

? { sequelize },

);


class Tag extends Model {}

Tag.init(

? {

? ? id: {

? ? ? primaryKey: true,

? ? ? type: DataTypes.INTEGER,

? ? ? autoIncrement: true,

? ? ? allowNull: false,

? ? },

? ? name: DataTypes.STRING,

? },

? { sequelize },

);


Service.belongsToMany(Tag, { through: 'Service_Tag', as: 'tags' });

Tag.belongsToMany(Service, { through: 'Service_Tag', as: 'services' });


(async function test() {

? try {

? ? await sequelize.sync({ force: true });

? ? //seed

? ? await Service.bulkCreate(

? ? ? [

? ? ? ? { name: 'Restaurant X', slug: 'a', tags: [{ name: 'restaurant' }, { name: 'b' }] },

? ? ? ? { name: 'Restaurant Y', slug: 'b', tags: [{ name: 'c' }] },

? ? ? ? { name: 'Restaurant Z', slug: 'c', tags: [{ name: 'restaurant' }] },

? ? ? ],

? ? ? { include: [{ model: Tag, as: 'tags' }] },

? ? );

? } catch (error) {

? ? console.log(error);

? }

})();


export { Service, Tag };

app.ts:


import { ApolloServer, gql } from 'apollo-server';

import * as models from './model';


const typeDefs = gql`

? type Tag {

? ? id: ID!

? ? name: String!

? }


? type Service {

? ? id: ID!

? ? name: String!

? ? slug: String!

? ? tags: [Tag!]!

? }


? type Query {

? ? findServicesByTag(tag: String!): [Service]!

? }

`;


const resolvers = {

? Query: {

? ? async findServicesByTag(_, { tag }, { models }) {

? ? ? const res = await models.Service.findAll({

? ? ? ? where: {

? ? ? ? ? '$tags.name$': tag,

? ? ? ? },

? ? ? ? include: [

? ? ? ? ? {

? ? ? ? ? ? model: models.Tag,

? ? ? ? ? ? as: 'tags',

? ? ? ? ? },

? ? ? ? ],

? ? ? });

? ? ? const data = res.map((v) => v.get({ plain: true }));

? ? ? return data;

? ? },

? },

};


const server = new ApolloServer({

? typeDefs,

? resolvers,

? context: {

? ? models,

? },

});


server.listen().then(({ url }) => {

? console.log(`??? Server ready at ${url}`);

});

使用以下命令測試 GraphQl 查詢curl:


??? curl 'http://localhost:4000/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'Origin: chrome-extension://flnheeellpciglgpaodhkhmapeljopja' --data-binary '{"query":"\nquery{\n? findServicesByTag(tag: \"restaurant\"){\n? ? id\n? ? name\n? ? slug\n? ? tags {\n? ? ? \tname\n\t\t}\n? }\n}","variables":{}}' --compressed

{"data":{"findServicesByTag":[{"id":"1","name":"Restaurant X","slug":"a","tags":[{"name":"restaurant"}]},{"id":"3","name":"Restaurant Z","slug":"c","tags":[{"name":"restaurant"}]}]}}

數據庫中的數據記錄:


node-sequelize-examples=# select * from "Service";

?id |? ? ?name? ? ?| slug?

----+--------------+------

? 1 | Restaurant X | a

? 2 | Restaurant Y | b

? 3 | Restaurant Z | c

(3 rows)


node-sequelize-examples=# select * from "Tag";

?id |? ? name? ??

----+------------

? 1 | restaurant

? 2 | b

? 3 | c

? 4 | restaurant

(4 rows)

node-sequelize-examples=# select * from "Service_Tag";

?ServiceId | TagId?

-----------+-------

? ? ? ? ?1 |? ? ?1

? ? ? ? ?1 |? ? ?2

? ? ? ? ?2 |? ? ?3

? ? ? ? ?3 |? ? ?4

(4 rows)


查看完整回答
反對 回復 2023-09-28
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號