Apollo
GitbookGraphql2021-01-11
๐ 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/awaitworks with most loops, but wonโt work with loops that require a callback.- For example,
for(),for-ofworks, butforEach,map,filter, andreduceNOT. forEachis not promise-aware. It cannot supportasyncandawait. You cannot useawaitinforEach.-
map:const promises = ary.map(async item => Promise.resolve(item)) await Promise.all(promises)
๐ Key Takeaways
- If you want to execute
awaitcalls in series, use afor-loop(or any loop without a callback). - Donโt ever use
awaitwithforEach. Use afor-loop(or any loop without a callback) instead. - Donโt
awaitinsidefilterandreduce. Alwaysawaitan array of promises withmap, thenfilterorreduceaccordingly.
๐ Sequelize
bin/init_db.sh:
$ npm install -g sequelize-cli- create
- update, save
- findAll
- findByPk
- findOne
- findOrCreate
- findAndCountAll
- count
- max
- min
- sum
๐ Reference
- apllographql
fullstack-tutorialfinal branch - graphql-bookstore
๐ Steps
- utils.js
- databases/
- resolver.js
- schema.js
- server.js
- Setup DB, here is
sqlite3: Not usesequelize initto createconfigs/andmodels/folders, just a simpleutils.js - create models:
defineSqlite3-Schema inutils.js - inside
databases/folder, extendsapollo-datasourceclass to implementcrud - define apollo-server
schema.js, mappingutils.jssqlite3 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.
