์์ฆ ์ฑ์ฉ๊ณต๊ณ ๋ฅผ ๋ณด๋ฉด, ๊ธฐ์ ์คํ(skills)์ graphQL ์ด๋ผ๋ ํค์๋๋ฅผ ๋ณด์์ ๊ฑฐ๋ค.
์ผ๋จ, graphQL ์ด ๋ญ์ง๋ถํฐ ์์๋ณด์!
over-fetching : API ์กฐํ๋ฅผ ํ๋ฉด, ํ์์๋ ๋ฐ์ดํฐ๊น์ง ๊ฐ์ง๊ณ ์ด
under-fetching : API ์กฐํ๋ฅผ ํ๋ฉด, ์ถฉ๋ถํ ๋ฐ์ดํฐ๊ฐ ์์ด์ ๋ค๋ฅธ API๋ฅผ ํธ์ถํ์ฌ ๋ฐ์ดํฐ๋ฅผ ์กฐํฉํจ
// ์คํค๋ง
type Query {
info: String!
feed: [Link!]!
person: [Person!]!
}
type Mutation {
createLink(url: String!, description: String!): Link!
updateLink(targetId: ID!, url: String, description: String): Link
deleteLink(targetId: ID!): LinkResult
createPerson(userName: String, userPassword: String): Person
}
type LinkResult {
msg: String!
}
type Link {
id: ID!
description: String!
url: String!
}
type Person {
user_id : ID!
user_name : String
user_password : String
}
// resolver
const resolvers = {
// ์กฐํ(R)
Query: {
info: () => `info ๋ฅผ ์กฐํํ๋ค?`,
feed: () => links,
person: async () => {
const result = await new Promise(((resolve, reject) => {
const query = `SELECT * FROM person`;
db.all(query, [], (err, rows) => {
if (err) {
console.log(err);
reject({err});
return false;
}
resolve([...rows]);
});
}));
if (result.hasOwnProperty('err')) {
return [];
} else {
return [...result];
}
}
},
// ์์ฑ, ๋ณ๊ฒฝ, ์ญ์ (CUD)
Mutation: {
createLink: (parent, args) => {
const link = {
id: `link-${idCount++}`,
description: args.description,
url: args.url,
};
links.push(link);
return link;
},
updateLink: (parent, {targetId, description, url}) => {
const targetLink = links.find(link => link.id === targetId);
targetLink.description = description ? description : '';
targetLink.url = url ? url : '';
return targetLink;
},
deleteLink: (parent, {targetId}) => {
const targetLinkIndex = links.findIndex(link => link.id === targetId);
if (targetLinkIndex != -1) {
links.splice(targetLinkIndex, 1);
return {
msg: 'success'
}
} else {
return {
msg: 'undefined'
}
}
},
createPerson: async (parent, {userName, userPassword}) => {
// https://www.sqlitetutorial.net/sqlite-nodejs/insert/
const result = await new Promise((resolve, reject) => {
const query = `INSERT INTO person (user_name, user_password) VALUES (?,?)`;
const selectQuery = `SELECT * FROM person WHERE user_id=?`;
db.run(query, [userName, userPassword], function (err) {
// success ์, this ์ lastID, changes ์์ฑ์ด ์๋ค.
if (err) {
console.log(`err : ${err}`);
reject({err});
return false;
}
db.get(selectQuery, [this.lastID], function (err, row) {
if (err) {
console.log(`err : ${err}`);
reject({err});
return false;
}
resolve({...row});
});
});
});
if (result.hasOwnProperty('err')) {
return {
user_id: -1,
user_name: 'error',
user_password: ''
}
} else {
return {...result};
}
}
},
// Link: {
// id: parent => parent.id,
// description: parent => parent.description,
// url: parent => parent.url
// }
};