Apollo

GitbookGraphql2021-01-11


๐Ÿ“‘ Apollo Server


Apollo Server

for (const [name, value] of Object.entries(option.headers)) {
	res.setHeader(name, value)
}

function getMiddleware({ path, cors, bodyParser } = {}) {
	const router = express.Router()
	router.use(path, (_req, _res, next) => {
		Promise.resolve()
			.then(next)
			.catch(next)
	})
}

๐Ÿ“‘ async, await


  • async/await works with most loops, but wonโ€™t work with loops that require a callback.
  • For example, for(), for-of works, but forEach, map, filter, and reduce NOT.
  • forEach is not promise-aware. It cannot support async and await. You cannot use await in forEach.
  • map:

    const promises = ary.map(async item => Promise.resolve(item))
    
    await Promise.all(promises)

๐Ÿ“‘ Key Takeaways


  1. If you want to execute await calls in series, use a for-loop (or any loop without a callback).
  2. Donโ€™t ever use await with forEach. Use a for-loop (or any loop without a callback) instead.
  3. Donโ€™t await inside filter and reduce. Always await an array of promises with map, then filter or reduce accordingly.

๐Ÿ“‘ Sequelize


bin/init_db.sh:

$ npm install -g sequelize-cli
  • create
  • update, save
  • findAll
  • findByPk
  • findOne
  • findOrCreate
  • findAndCountAll
  • count
  • max
  • min
  • sum

๐Ÿ“‘ Reference


  1. apllographql fullstack-tutorial final branch
  2. graphql-bookstore

๐Ÿ“‘ Steps


  • utils.js
  • databases/
  • resolver.js
  • schema.js
  • server.js
  • Setup DB, here is sqlite3: Not use sequelize init to create configs/ and models/ folders, just a simple utils.js
  • create models: define Sqlite3-Schema in utils.js
  • inside databases/ folder, extends apollo-datasource class to implement crud
  • define apollo-server schema.js, mapping utils.js sqlite3 schema.
  • define resolver.js, associate databases-middleware with schema/utils.
  • inject to apollo-server: {typeDefs, resolvers, datasources}
  • test

๐Ÿช• QA:


  • There are at least two GraphQL clients available:

    • Relay, the former implementation by Facebook, highly tangled together with React;
    • Apollo, which strives to be a framework-agnostic (ไธๅฏ็Ÿฅ่ฎบ็š„) project.