hypercore-protocol / p2p-multiwriter-with-autobase

p2p posting & voting workshop
69 stars 15 forks source link

Uncaught SyntaxError: await is only valid in async function in Problem 5, 6 and 7 #5

Closed raphael10-collab closed 3 years ago

raphael10-collab commented 3 years ago
(base) raphy@pc:~/hypercore/p2p-multiwriter-with-autobase/solutions/06$ hrepl hypernews.js
Autobase setup. Pass this to run this same setup in another instance:

hrepl hypernews.js -n 97526323adf7b9c4 -w 97526323adf7b9c40f72daa280646051d539b757e4b03cf5a3e8b3c5f8defac0 -i 68919658e1f6ffb83c013145fcd21c8323f636203cf427e16934e1a24a5d700c

To use another storage directory use --storage ./another
To disable swarming add --no-swarm

API: hypernews (object)
> await hypernews.post('hello world')
await hypernews.post('hello world')
^^^^^

Uncaught SyntaxError: await is only valid in async function
> hypernews.post('hello world')
Promise { <pending> }
> hypernews.post('sup earth')
Promise { <pending> }
> .log hypernews.all()
try { for await (const data of hypernews.all()) console.log(data) } catch { console.log(hypernews.all()) }
try { for await (const data of hypernews.all()) console.log(data) } catch { console.log(hypernews.all()) }
          ^^^^^

Uncaught SyntaxError: Unexpected reserved word
> 

This is the package.json file :

{
  "type": "module",
  "dependencies": {
    "autobase": "^1.0.0-alpha.0",
    "corestore": "^6.0.0-alpha.3",
    "hyperbee": "^1.6.3",
    "hyperswarm": "^3.0.0",
    "lexicographic-integer": "^1.1.0",
    "minimist": "^1.2.5",
    "random-access-memory": "^3.1.2"
  }
}

And this is the hypernews.js file :

import minimist from 'minimist'
import Corestore from 'corestore'
import Hyperswarm from 'hyperswarm'
import Autobase from 'autobase'
import Hyperbee from 'hyperbee'
import crypto from 'crypto'
import ram from 'random-access-memory'

const args = minimist(process.argv, {
  alias: {
    writers: 'w',
    indexes: 'i',
    storage: 's',
    name: 'n'
  },
  default: {
    swarm: true
  },
  boolean: ['ram', 'swarm']
})

class Hypernews {
  constructor () {
    this.store = new Corestore(args.ram ? ram : (args.storage || 'hypernews'))
    this.swarm = null
    this.autobase = null
    this.bee = null
    this.name = null
  }

  async start () {
    const writer = this.store.get({ name: 'writer' })
    const autobaseIndex = this.store.get({ name: 'index' })

    await writer.ready()

    this.name = args.name || writer.key.slice(0, 8).toString('hex')
    this.autobase = new Autobase([writer], { indexes: autobaseIndex })

    for (const w of [].concat(args.writers || [])) {
      await this.autobase.addInput(this.store.get(Buffer.from(w, 'hex')))
    }

    for (const i of [].concat(args.indexes || [])) {
      await this.autobase.addDefaultIndex(this.store.get(Buffer.from(i, 'hex')))
    }

    await this.autobase.ready()

    if (args.swarm) {
      const topic = Buffer.from(sha256(this.name), 'hex')
      this.swarm = new Hyperswarm()
      this.swarm.on('connection', (socket) => this.store.replicate(socket))
      this.swarm.join(topic)
      await this.swarm.flush()
      process.once('SIGINT', () => this.swarm.destroy()) // for faster restarts
    }

    this.info()

    const self = this
    const index = this.autobase.createRebasedIndex({
      unwrap: true,
      async apply (batch) {
        const b = self.bee.batch({ update: false })

        for (const { value } of batch) {
          const op = JSON.parse(value)

          if (op.type === 'post') {
            const hash = sha256(op.data)
            await b.put('posts!' + hash, { hash, votes: 0, data: op.data })
          }

          if (op.type === 'vote') {
            const inc = op.up ? 1 : -1
            const p = await self.bee.get('posts!' + op.hash, { update: false })

            if (!p) continue

            p.value.votes += inc
            await b.put('posts!' + op.hash, p.value)
          }
        }

        await b.flush()
      }
    })

    this.bee = new Hyperbee(index, {
      extension: false,
      keyEncoding: 'utf-8',
      valueEncoding: 'json'
    })
  }

  info () {
    console.log('Autobase setup. Pass this to run this same setup in another instance:')
    console.log()
    console.log('hrepl hypernews.js ' +
      '-n ' + this.name + ' ' +
      this.autobase.inputs.map(i => '-w ' + i.key.toString('hex')).join(' ') + ' ' +
      this.autobase.defaultIndexes.map(i => '-i ' + i.key.toString('hex')).join(' ')
    )
    console.log()
    console.log('To use another storage directory use --storage ./another')
    console.log('To disable swarming add --no-swarm')
    console.log()
  }

  async * all () {
    for await (const data of this.bee.createReadStream({ gt: 'posts!', lt: 'posts!~' })) {
      yield data.value
    }
  }

  async post (text) {
    const hash = sha256(text)

    await this.autobase.append(JSON.stringify({
      type: 'post',
      hash,
      data: text
    }))
  }

  async upvote (hash) {
    await this.autobase.append(JSON.stringify({
      type: 'vote',
      hash,
      up: true
    }))
  }

  async downvote (hash) {
    await this.autobase.append(JSON.stringify({
      type: 'vote',
      hash,
      up: false
    }))
  }
}

export const hypernews = new Hypernews()

await hypernews.start()

function sha256 (inp) {
  return crypto.createHash('sha256').update(inp).digest('hex')
}

I'm having the same issue also with Problem 7 and actually with Problem 5

(base) raphy@pc:~/hypercore/p2p-multiwriter-with-autobase/solutions/07$ hrepl hypernews.js 
Autobase setup. Pass this to run this same setup in another instance:

hrepl hypernews.js -n 3a7b3e991f6bff18 -w 3a7b3e991f6bff18cb415292991f62244c35dad7eec0632364e0ee346d1b7d21 -i cb8286a188f26d1589f7e61f5f6119b40a069895270c8d9520bea88981c48283

To use another storage directory use --storage ./another
To disable swarming add --no-swarm

API: hypernews (object)
> await hypernews.post('hello world')
await hypernews.post('hello world')
^^^^^

Uncaught SyntaxError: await is only valid in async function
> hypernews.post('hello world')
Promise { <pending> }
> hypernews.post('sup earth')
Promise { <pending> }
> .log hypernews.all()
try { for await (const data of hypernews.all()) console.log(data) } catch { console.log(hypernews.all()) }
try { for await (const data of hypernews.all()) console.log(data) } catch { console.log(hypernews.all()) }
          ^^^^^

Uncaught SyntaxError: Unexpected reserved word
> 
mafintosh commented 3 years ago

You need a very recent version of node for the repl stuff. You on 16?

raphael10-collab commented 3 years ago

v14.15.5 is not enough?

mafintosh commented 3 years ago

Try 16, worked for everyone in the workshop

raphael10-collab commented 3 years ago

Yes. With node v.16.13.0 works fine. Thank you

mafintosh commented 3 years ago

\o/