首页 > 解决方案 > 无法在 typescript 中配置 Apolloserver 的数据源

问题描述

我对 TypeScript 和 Apollo 很陌生。我第一次尝试设置我的 Apollo 服务器,但我不断收到有关“数据源”的错误消息。我不确定这意味着什么以及如何解决它。

import  { ApolloServer, gql } from 'apollo-server';
//...
const { RESTDataSource } = require('apollo-datasource-rest');

class MoviesAPI extends RESTDataSource {
  constructor() {
    super();
    this.baseURL = 'https://movies-api.example.com/';
  }

  async getMovie(id) {
    return this.get(`movies/${id}`);
  }

  async getMostViewedMovies(limit = 10) {
    const data = await this.get('movies', {
      per_page: limit,
      order_by: 'most_viewed',
    });
    return data.results;
  }
}


const SERVERCONFIG = {
  'typeDefs': gql(typeDefs) ,
  resolvers,
  dataSources: ()=> ({
      MoviesAPI:  new MoviesAPI(),
  }  ) ,
};

const server = new ApolloServer(SERVERCONFIG);

我收到以下错误:

Type '{ 'typeDefs': DocumentNode; resolvers: { Query: {}; }; dataSources: () => { MoviesAPI: MoviesAPI; }; }' is not assignable to type 'ApolloServerExpressConfig'.
    The types returned by 'dataSources()' are incompatible between these types.
      Type '{ MoviesAPI: MoviesAPI; }' is not assignable to type 'DataSources<object>'.
        Property 'MoviesAPI' is incompatible with index signature.
          Type 'MoviesAPI' has no properties in common with type 'DataSource<object>'.

如果我执行以下操作,我可以让错误消失:dataSources: ()=> ({...MoviesAPI}) 但我认为这不能解决问题...

有谁知道是什么原因造成的?

标签: javascripttypescriptgraphqlapolloapollo-server

解决方案


改变

const { RESTDataSource } = require('apollo-datasource-rest');

import { RESTDataSource } from 'apollo-datasource-rest';

这应该会为您解决。


推荐阅读