在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):tmeasday/create-graphql-server开源软件地址(OpenSource Url):https://github.com/tmeasday/create-graphql-server开源编程语言(OpenSource Language):JavaScript 87.8%开源软件介绍(OpenSource Introduction):Create GraphQL ServerCreate-graphql-server is a scaffolding tool that lets you generate a new Mongo/Express/Node.js GraphQL server project from the command line. After generating the project you can also generate code to support your GraphQL schema directly from the schema files. Basic authentication support is included via Passport Local with JWTs. NOTE: this project is not actively maintained. As a scaffolding tool, this is not necessarily an issue (you can generate a project with it and then forget about the tool), but it is increasingly falling out of date. A spritiual successor is the Getting StartedInstallationInstall it once globally: npm install -g create-graphql-server Creating a ServerTo create a new server in the my-new-server-dir folder use the init command: create-graphql-server init my-new-server-dir
cd my-new-server-dir
yarn install Starting the ServerIn most development environments you can now fire up your new server using the packaged prebuilt Mongo server: yarn start If mongo-prebuilt fails to start, or you'd rather use another MongoDB installation for development, simply set the # On Windows:
SET MONGO_URL=mongodb://localhost:27017&&yarn start
# On Unix/OSX:
MONGO_URL=mongodb://localhost:27017 yarn start If you set up a username, password or a different port for Mongo, or are accessing Mongo through a service such as mLab, correct the MONGO_URL above to reflect that. Running QueriesYour server is now up and running. To query it, point your browser at http://localhost:3010/graphiql. There isn't anything to query yet however. Adding Types: OverviewTo add types, you can define them in GraphQL schema files, then generate code for them using the add-type command, as follows: create-graphql-server add-type path/to/my-new-type.graphql If you have a folder full of schema files, you can add them all at once by pointing add-type to a folder instead of an individual schema file: create-graphql-server add-type path Sample schema files are included in SchemasYou create a GraphQL type for your schema by specifying the type as input, with some special code-generation controlling directives. For example, in type User {
email: String!
bio: String
tweets: [Tweet!] @hasMany(as: "author")
liked: [Tweet!] @belongsToMany
following: [User!] @belongsToMany
followers: [User!] @hasAndBelongsToMany(as: "following")
} The above will generate a User type which is linked to other users and a tweet type via foriegn keys and which will have mutations to add, update and remove users, as well as some root queries to find a single user or all users. The directives used control the code generation (see below). Directives
RelationsIf types reference each other, you should use an association directive to explain to the generator how the reference should be stored in mongo: Singleton fieldsIf the field references a single (nullable or otherwise) instance of another type, it will be either:
Paginated fieldsIf the field references an array (again w/ or w/o nullability) of another type, it will be either:
Updating typesTo update types, just re-run add-type again: create-graphql-server add-type path/to/input.graphql [--force-update] This overwrites your old type specific files from the directories: schema, model, resolvers. It recognizes, if you've changed any code file, which will be overwritten by the generator and stops and warns. If you are sure, you want to overwrite your changes, then just use the --force-update option. Removing typesTo remove types, use the following command with the path to the GraphQL file, or as alternative, just enter the type name without path. create-graphql-server remove-type path/to/input.graphql
create-graphql-server remove-type typename
create-graphql-server remove-type path This command deletes your old type specific files from the directories: schema, model, resolvers. It also removes the code references out of the corresponding index files. It recognizes, if you've changed any code file, which will be overwritten by the generator and stops and warns. If you are sure, you want to overwrite your changes, then just use the force-update option. AuthenticationCGS sets up a basic passport-based JWT authentication system for your app. NOTE: you should ensure users connect to your server through SSL. To use it, ensure you have a GraphQL type called type User {
email: String!
bio: String
} You could update the generated input CreateUserInput {
email: String!
password: String! # <- you need to add this line to the generated output
bio: String
} And then update the generated import bcrypt from 'bcrypt';
// Set this as appropriate
const SALT_ROUNDS = 10;
class User {
async insert(doc) {
// We don't want to store passwords plaintext!
const { password, ...rest } = doc;
const hash = await bcrypt.hash(password, SALT_ROUNDS);
const docToInsert = Object.assign({}, rest, {
hash,
createdAt: Date.now(),
updatedAt: Date.now(),
});
// This code is unchanged.
const id = (await this.collection.insertOne(docToInsert)).insertedId;
this.pubsub.publish('userInserted', await this.findOneById(id));
return id;
}
} Client side codeTo create users, simply call your generated To login on the client, you make a RESTful request to Here's some code to do just that: const KEY = 'authToken';
let token = localStorage.getItem(KEY);
const networkInterface = createNetworkInterface(/* as usual */);
networkInterface.use([
{
applyMiddleware(req, next) {
req.options.headers = {
authorization: token ? `JWT ${token}` : null,
...req.options.headers,
};
next();
},
},
]);
// Create your client as usual and pass to a provider
const client = /*...*/
// Call this function from your login form, or wherever.
const login = async function(serverUrl, email, password) {
const response = await fetch(`${serverUrl}/login`, {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: { 'Content-Type': 'application/json' },
});
const data = await response.json();
token = data.token;
localStorage.setItem(KEY, token);
} DevelopmentRunning code generation testsYou can run some basic code generation tests with Testing full app code generationA simple test to check that using the Running end-to-end testsYou can run a set of end-to-end tests of the user/tweet app (which lives in The test files are in You need to start the standard server with Creating seed databaseIf you need to change the fixtures for the test db Start the server, then run mongoexport --host 127.0.0.1:3002 --db database --collection user > seeds/User.json
mongoexport --host 127.0.0.1:3002 --db database --collection tweet > seeds/Tweet.json MaintenanceAs this is a code generator, and not a library, once you run the code, you are on your own :) By which I mean, you should feel free to read the generated code, understand it, and modify it as you see fit. Any updates to CGS will just affect future apps that you generate. If you'd like to see improvements, or find any bugs, by all means report them via the issues, and send PRs. But workarounds should be always be possible simply by patching the generated code. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论