通过node js脚本在服务器端运行GraphQL突变(Apollo)。

问题描述 投票:-1回答:1

我正在运行一个scraping脚本(Puppeteer),并希望将每个scraping的行写入数据库。

目前我得到了这个错误。

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

以下是我代码的相关部分

import puppeteer from 'puppeteer'
import $ from 'cheerio'
import { useMutation } from '@apollo/react-hooks'
import moment from 'moment'
import gql from 'graphql-tag'

const ADD_RESULT = gql`
  mutation CreateOneResult( $site: String!, $status: String!, $link: String!, $name: String, $publication: String, $decision: String, $clause: String, $commentText: String, $decisionText: String, $noDateReceived: Boolean, $dateReceived: DateTime, $noDateConcluded: Boolean, $dateConcluded: DateTime! ) {
    createOneResult(data: {
        site: $site,
        status: $status,
        link: $link,
        name: $name,
        publication: $publication,
        decision: $decision,
        clause: $clause,
        commentText: $commentText,
        decisionText: $decisionText,
        noDateReceived: $noDateReceived,
        dateReceived: $dateReceived,
        noDateConcluded: $noDateConcluded,
        dateConcluded: $dateConcluded,
    }){
        id
    }
  }
`

/**
 * Loop results and follow the link, scraping extra info
 */
export async function doExtraScrapeStepsAndAddToDB(results) {

    results = await (async () => {
        var updatedResults = []
        for (let i = 0; i < results.length; i++) {
            let result = results[i]
            let extraResultInfo = await module.exports.getExtraPageInfoFromLink(result)

            if (extraResultInfo) {
                let updatedResultInfo = { ...result, ...extraResultInfo }
                let added = await addResultToDB(updatedResultInfo)
                console.log(`Added result of ID ${added} to the database`)
                updatedResults.push(updatedResultInfo)
            }
        }
        return updatedResults
    })()

    return results
}

/**
 * Add result to DB
 */
export async function addResultToDB(result) {
    const [CreateOneResult] = useMutation(ADD_RESULT)

    return await CreateOneResult({
        variables: {
            ...result,
            ...(false == result.noDateConcluded && {
                dateReceived: moment(result.dateConcluded, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
            }),
            ...(false == result.noDateReceived && {
                dateReceived: moment(result.dateReceived, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
            }),
        }
    })
}
  • doExtraScrapeStepsAndAddToDB 被称为
  • 它通过以下方式为每个结果抓取一些进一步的信息(从另一个URL)。getExtraPageInfoFromLink
  • 最后,将完成的结果通过 addResultToDB

我打算在前端使用GraphQL(Apollo),所以觉得可以通过在后端使用GraphQL突变写到DB,在这个搜刮脚本中进行练习。

我不太明白这个错误的本质,除了这个 useMutation 函数只能在函数组件(?)中使用。如果是这样的话,这里有什么办法呢?

我正在使用

  • GraphQL
  • Nexus
  • Prisma
  • 阿波罗

先谢谢你

node.js reactjs next.js react-apollo prisma-graphql
1个回答
0
投票

用这个解决了。

import fetch from 'node-fetch'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { createHttpLink } from 'apollo-link-http'

const client = new ApolloClient({
        link: createHttpLink({
            uri: 'http://localhost:3000/api/graphql',
            fetch: fetch
        }),
        cache: new InMemoryCache()
    });

return await client.mutate({
        mutation: ADD_RESULT,
        variables: {
            ...result,
            ...(false == result.noDateConcluded && {
                dateReceived: moment(result.dateConcluded, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
            }),
            ...(false == result.noDateReceived && {
                dateReceived: moment(result.dateReceived, 'DD/MM/YYYY').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
            }),
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.