用 express 建立簡單 GraphQL server(postgresql 資料庫)

建立 Project

init 一個 project

$npm init -y

建立 es6 babel

$npm install babel-cli babel-preset-env babel-watch --save

建立 .babelrc

{
	 "presets": ["env"]
}

修改 package.json

{
	// ....
	 "scripts": {
		"dev": "babel-watch server.js",
		"test": "echo \"Error: no test specified\" && exit 1"
	},
	// ....
}

確認 postgresql table

[email protected]~$ psql -d nodetest
psql (9.6.9)
Type "help" for help.

nodetest=# select id, username, email from users;
 id | username |         email          
----+----------+------------------------
	4 | Brian    | [email protected]
 14 | Cathy    | [email protected]
	1 | Jerry    | [email protected]
 33 | Irene    | [email protected]
(4 rows)

加入 express, postgresql 跟 graphql

$npm install express cors pg-promise --save
$npm install graphql graphql-tools apollo-server-express --save

server.js

import express from 'express';
import bodyParse from 'body-parser';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import cors from 'cors';

//import schema from './schema';
import schema from './pg-schema';

const app = express();

app.use('*', cors());

app.use('/graphiql', graphiqlExpress({
	endpointURL: "/graphql"
}));

app.use('/graphql', bodyParse.json(), graphqlExpress({ schema }));

app.listen(4000, () => console.log("express server running on port 4000 "));

使用 cors() middleware 避免 cors 問題

endpoint 有 /graphiql/graphql

pg-schema.js

import { makeExecutableSchema } from 'graphql-tools';
import resolvers from './pg-resolver';

const typeDefs = [`
	 type User {
			id: String
			username: String
			email: String
	 }
	 type Query {
			users: [User]
	 }
`];

const schema = makeExecutableSchema({
	typeDefs,
	resolvers
});

export default schema;

定義 schema

pg-resolver.js

import psql from './psql-adapter';

const resolvers = {
	Query: {
		users: () => {
			const userQuery = 'select id, username, email from users';
			return psql.manyOrNone(userQuery);
		}
	}
}

export default resolvers;

簡單 resolver, sql 來 query user table

psql-adapter.js

import pgPromise from 'pg-promise';

const connectStr = {
	host: 'localhost',
	port: 5432,
	database: 'nodetest',
	user: 'xxxxx',
	password: 'yyyy'
};

const pgp = pgPromise({});
const psql = pgp(connectStr);

export default psql;

執行 server

[email protected] dev /Users/jerryhsieh/Developer/Web/graphql/graphql-nodejs
> babel-watch server.js

express server running on port 4000
>>> RESTARTING <<< express server running on port 4000 [/sourcecode]

未命名_2018-07-02_15-08-16.png

Notice: compact(): Undefined variable: limits in /var/www/html/wp-includes/class-wp-comment-query.php on line 853 Notice: compact(): Undefined variable: groupby in /var/www/html/wp-includes/class-wp-comment-query.php on line 853

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *