我正在做阿波罗服务器的GraphQL教程。现在,我正在尝试从这个部分添加批处理- https://www.apollographql.com/docs/apollo-server/features/data-sources/#batching。
我知道我可以在private中使用TypeScript。但不确定如何在JS中使用。
据我所搜索,我安装了两个babel插件,class-properties和private-methods。
// .babelrc
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
["@babel/plugin-proposal-class-properties", { "loose": true }],
["@babel/plugin-proposal-private-methods", { "loose": true }],
"@babel/plugin-proposal-object-rest-spread",
"@babel/plugin-proposal-async-generator-functions"
]
}下面是代码:
// datasource.js
import DataLoader from 'dataloader';
class PostAPI extends DataSource {
constructor({ knex }) {
super();
this.knex = knex;
}
initialize(config) {
this.context = config.context;
}
// ERROR HERE!
#postLoader = new DataLoader(ids =>
this.knex('posts')
.whereIn('id', ids)
.select()
.then(rows => ids.map(id => rows.find(x => x.id === id)))
);
async findAll() {
const posts = await this.knex('posts').select();
if (!posts.length) return [];
console.log(posts);
return posts;
}
async findOne({ id: idArg } = {}) {
/*
const post = await this.knex('posts')
.where('id', idArg)
.first();
*/
const post = await this.postLoader.load(idArg);
if (!post) return;
return post;
}
}当我查询单个post (FindOne)时,它会产生错误:
{
"errors": [
{
"message": "Cannot read property 'load' of undefined",
}
]
}此外,eslint警告说#是“无效字符”。
这是我的.eslintrc
// .eslintrc.json
{
"root": true,
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2018,
"allowImportExportEverywhere": false,
"ecmaFeatures": {
"globalReturn": false
}
},
"plugins": ["babel"],
"extends": ["eslint:recommended", "prettier"],
"env": {
"browser": true,
"node": true,
"es6": true,
"jest": true
},
"rules": {},
"globals": {}
}请帮帮忙。
发布于 2019-07-20 16:03:13
#是字段名称的一部分。因此,您需要在任何地方使用#:
const post = await this.#postLoader.load(idArg);
// ---------------------^下面是一个使用私有字段(以及私有方法)的简单示例:
class Example {
#foo = 42;
publicMethod() {
console.log("From publicMethod:", this.#foo);
this.#privateMethod();
}
#privateMethod() {
console.log("From #privateMethod:", this.#foo);
}
}
const e = new Example();
console.log(e.publicMethod());此外,eslint警告#是“无效字符”。
私人领域仍然只是第三阶段的提案,还没有标准化。ESLint似乎没有支持它们的选择。
https://stackoverflow.com/questions/57126287
复制相似问题