在 getter 中更改类型 - 使用 graphql 续集
changing type in getter - sequelize with graphql
我试图在将数组保存到我的 mysql 数据库时对其进行字符串化,并在检索它时对其进行解析,但我得到了 "String cannot represent an array"。是否可以使用 sequelize 更改 getter 中的类型,如果可以,将如何完成?
choices: {
type:Sequelize.TEXT,
get(){
var val = this.getDataValue('choices');
return val ? JSON.parse(val):null;
},
set(val){
if(val && typeof(val)!=='string'){
val = JSON.stringify(val);
}
this.setDataValue('choices',val);
}
},
这不是 sequelize 或 mysql 的问题。这是我的 GraphQL 突变的问题,我不得不覆盖类型
import { attributeFields } from "graphql-sequelize";
import { GraphQLList, GraphQLString } from "graphql";
import { Question } from "../schemas/Question";
import ResponsePayload from "../schemas/ResponsePayload";
import _ from "lodash";
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
const CreateQuestion = {
type: ResponsePayload,
args: base,
resolve: ...
};
export { CreateQuestion };
特别是我必须改变
var base = attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
});
到
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
这会覆盖选择的类型,在 sequelize 模型中它被定义为一个字符串,但就 GraphQL 而言需要是一个数组。
我试图在将数组保存到我的 mysql 数据库时对其进行字符串化,并在检索它时对其进行解析,但我得到了 "String cannot represent an array"。是否可以使用 sequelize 更改 getter 中的类型,如果可以,将如何完成?
choices: {
type:Sequelize.TEXT,
get(){
var val = this.getDataValue('choices');
return val ? JSON.parse(val):null;
},
set(val){
if(val && typeof(val)!=='string'){
val = JSON.stringify(val);
}
this.setDataValue('choices',val);
}
},
这不是 sequelize 或 mysql 的问题。这是我的 GraphQL 突变的问题,我不得不覆盖类型
import { attributeFields } from "graphql-sequelize";
import { GraphQLList, GraphQLString } from "graphql";
import { Question } from "../schemas/Question";
import ResponsePayload from "../schemas/ResponsePayload";
import _ from "lodash";
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
const CreateQuestion = {
type: ResponsePayload,
args: base,
resolve: ...
};
export { CreateQuestion };
特别是我必须改变
var base = attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
});
到
var base = _.assign(attributeFields(sequelize.models.question, {
exclude: ["id", "createdAt", "updatedAt"]
}), { choices: { type: new GraphQLList(GraphQLString) }});
这会覆盖选择的类型,在 sequelize 模型中它被定义为一个字符串,但就 GraphQL 而言需要是一个数组。