Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
Nextjs, Apollo client và apollo server tất cả trong một Express server
Getting started
Chào mọi người, tiện tại mình đang cần làm một ứng dụng siêu siêu nhỏ cute hột me kiểu addons, plugin... Với những ứng dụng nhỏ nhỏ cần triển khai nhanh gọn lẹ kiểu kiểu thế này, thì mình sẽ nghĩ đến mô hình monorepo..kiểu như tất cả trong 1 ấy... thế cho nó gọn ;)
Thành phần bao gồm:
- Phần server: Làm nodejs express cho nhẹ...lại nhanh nữa.
- Database thì mình xài MySQL, vì cảm thấy cần quản lý dữ liệu quan hệ.
- Frontend thì xài Nextjs với React. Server-side rendering bởi vì mình cần xào nấu data bọn API trả về trước khi quăng ra React
- API Gateway: Có điểm lưu ý ở đây là mình xài Graphql để làm API gateway, bởi vì app của mình có thể sẽ phải kết nối với nhiều cái API khác. Phần Apollo server thì để phía Nodejs, Apollo client thì cho luôn vô Nextjs cho nó tiện.
Đại khái mô hình nó sẽ là thế này.
Folder structure
Sẽ chia làm 3 cục cho nó dễ quản lý. Đơn giản là dùng yarn workspaces thôi
root
|- packages
| |- client
| |- graphql
| |- server
|- package.json
|- yarn.lock
Setup Apollo server
Phần này mình xài khá nhiều đồ chơi, chắc sẽ tách ra một bài riêng để chém gió. Còn ngắn gọn thì sau khi setup các kiểu sẽ export thằng apollo server để sau đó import vô Express
const server = new ApolloServer({
typeDefs: schema,
resolvers,
schemaDirectives,
playground: true,
context: ({ req }) => {
let nreq = <any>req;
let user = nreq.user;
return {
[EXPECTED_OPTIONS_KEY]: createContext(sequelize),
user: user,
};
}
});
export default server
Setup Apollo client
Phần này tiện cái là Nextjs có example rồi...bê nguyên cái example vô là xong he he
Đây là example của nó: next.js/examples/with-apollo
export default function createApolloClient(initialState, ctx) {
return new ApolloClient({
ssrMode: Boolean(ctx),
link: new HttpLink({
uri: process.env.GRAPHQL_URI, // must be absolute for SSR to work
credentials: 'same-origin',
fetch,
}),
cache: new InMemoryCache().restore(initialState),
});
}
Setup Express server
Cái chỗ này quan trọng nhất nè All in one sẽ nằm ở đây. Route '/graphql' sẽ được handle bởi Apollo server. Những route còn lại sẽ được handle bởi Nextjs.
Chỗ này sẽ lôi thằng apollo server lúc nãy và thằng nextjs ra và integrate vô express :D
import express from 'express';
import nextApp from '@monorepo/client';
import apolloServer from '@monorepo/graphql';
const PORT = process.env.PORT || '3000';
async function main() {
const app = express();
await bootstrapApolloServer(app);
await bootstrapClientApp(app);
app.listen(PORT, (err) => {
if (err) throw err;
console.log(`[ server ] ready on port ${PORT}`);
});
}
async function bootstrapClientApp(expressApp) {
await nextApp.prepare();
expressApp.get('*', nextApp.getRequestHandler());
}
async function bootstrapApolloServer(expressApp) {
apolloServer.applyMiddleware({ app: expressApp });
}
Run
Ok rồi, mình yarn install và yarn start để chạy thử
Còn đây là link repo: express-apollo-nextjs ae chạy thử và cho ít gạch để hoàn thiện hơn
woowebsite 01-06-2020




