{"id":14976191,"url":"https://github.com/tmeasday/create-graphql-server","last_synced_at":"2025-04-09T15:10:05.527Z","repository":{"id":71273764,"uuid":"73671752","full_name":"tmeasday/create-graphql-server","owner":"tmeasday","description":"Generate your GraphQL server one type at a time","archived":false,"fork":false,"pushed_at":"2018-03-01T01:21:11.000Z","size":384,"stargazers_count":321,"open_issues_count":18,"forks_count":21,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-09T15:09:59.973Z","etag":null,"topics":["codegeneration","graphql","graphql-server","mongodb"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tmeasday.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-11-14T05:59:08.000Z","updated_at":"2024-12-11T15:44:44.000Z","dependencies_parsed_at":"2023-02-22T12:15:30.662Z","dependency_job_id":null,"html_url":"https://github.com/tmeasday/create-graphql-server","commit_stats":{"total_commits":101,"total_committers":7,"mean_commits":"14.428571428571429","dds":"0.12871287128712872","last_synced_commit":"51e0fbf073291fbae5b0ca4e69f7983b2b434c04"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmeasday%2Fcreate-graphql-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmeasday%2Fcreate-graphql-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmeasday%2Fcreate-graphql-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmeasday%2Fcreate-graphql-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tmeasday","download_url":"https://codeload.github.com/tmeasday/create-graphql-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248055282,"owners_count":21040157,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codegeneration","graphql","graphql-server","mongodb"],"created_at":"2024-09-24T13:53:28.296Z","updated_at":"2025-04-09T15:10:05.496Z","avatar_url":"https://github.com/tmeasday.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Create GraphQL Server\n\n*Create-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. \n\n**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 [`graphql-cli`](https://github.com/graphql-cli/graphql-cli) project. Please take a look!\n\n## Getting Started\n\n### Installation\n\nInstall it once globally:\n```bash\nnpm install -g create-graphql-server\n```\n\n### Creating a Server\nTo create a new server in the *my-new-server-dir* folder use the *init* command:\n```bash\ncreate-graphql-server init my-new-server-dir\ncd my-new-server-dir\nyarn install\n```\n\n### Starting the Server\nIn most development environments you can now fire up your new server using the packaged [prebuilt Mongo server](https://github.com/winfinit/mongodb-prebuilt):\n\n```bash\nyarn start\n```\n\nIf [mongo-prebuilt](https://github.com/winfinit/mongodb-prebuilt) fails to start, or you'd rather use another [MongoDB installation](https://docs.mongodb.com/manual/installation/) for development, simply set the `MONGO_URL` environment variable when you start the server, as follows:\n\n```bash\n# On Windows:\nSET MONGO_URL=mongodb://localhost:27017\u0026\u0026yarn start\n\n# On Unix/OSX:\nMONGO_URL=mongodb://localhost:27017 yarn start\n```\n\nIf you set up a username, password or a different port for Mongo, or are accessing Mongo through a service such as [mLab](https://mlab.com/), correct the MONGO_URL above to reflect that.\n\n## Running Queries\n\nYour server is now up and running. To query it, point your browser at [http://localhost:3010/graphiql](http://localhost:3010/graphiql). There isn't anything to query yet however. \n\n## Adding Types: Overview\nTo add types, you can define them in GraphQL schema files, then generate code for them using the *add-type* command, as follows:\n```bash\ncreate-graphql-server add-type path/to/my-new-type.graphql\n```\nIf 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:\n```bash\ncreate-graphql-server add-type path\n```\nSample schema files are included in [`test/input`](https://github.com/tmeasday/create-graphql-server/tree/master/test/input). To see what a complete generated server looks like using them, check out [`test/output-app`](https://github.com/tmeasday/create-graphql-server/tree/master/test/output-app).\n\n## Schemas\n\nYou create a GraphQL type for your schema by specifying the type as input, with some special code-generation controlling directives.\n\nFor example, in `User.graphql`:\n\n```graphql\ntype User {\n  email: String!\n  bio: String\n\n  tweets: [Tweet!] @hasMany(as: \"author\")\n  liked: [Tweet!] @belongsToMany\n\n  following: [User!] @belongsToMany\n  followers: [User!] @hasAndBelongsToMany(as: \"following\")\n}\n```\n\nThe 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.\n\nThe directives used control the code generation (see below).\n\n### Directives\n\n- `@unmodifiable` - the field will not appear in the update mutation\n- `@enum` - the field's type is an enum, and can be set directly (not just by `Id`).\n\n### Relations\n\nIf types reference each other, you should use an association directive to explain to the generator how the reference should be stored in mongo:\n\n#### Singleton fields\n\nIf the field references a single (nullable or otherwise) instance of another type, it will be either:\n\n- `@belongsTo` - the foreign key is stored on this type as `${fieldName}Id` [this is the default]\n- `@hasOne` - the foreign key is stored on the referenced type as `${typeName}Id`. Provide the `\"as\": X` argument if the name is different. [NOTE: this is not yet fully implemented].\n\n#### Paginated fields\n\nIf the field references an array (again w/ or w/o nullability) of another type, it will be either:\n\n- `@belongsToMany` - there is a list of foreign keys stored on this type as `${fieldName}Ids` [this is the default]\n- `@hasMany` - the foreign key is on the referenced type as `${typeName}Id`. Provide the `\"as\": X` argument if the name is different. (this is the reverse of `@belongsTo` in a 1-many situation).\n- `@hasAndBelongsToMany` - the foreign key on the referenced type as `${typeName}Ids`. Provide the `\"as\": X` argument if the name is different. (this is the reverse of `@belongsToMany` in a many-many situation).\n\n## Updating types\n\nTo update types, just re-run add-type again:\n\n```bash\ncreate-graphql-server add-type path/to/input.graphql [--force-update]\n```\n\nThis overwrites your old *type* specific files from the directories: schema, model, resolvers.\n\nIt 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.\n\n## Removing types\n\nTo remove types, use the following command with the path to the GraphQL file, or as alternative, just enter the type name without path.\n\n```bash\ncreate-graphql-server remove-type path/to/input.graphql\n\ncreate-graphql-server remove-type typename\n\ncreate-graphql-server remove-type path\n```\n\nThis 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.\n\nIt 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.\n\n## Authentication\n\nCGS sets up a basic passport-based JWT authentication system for your app.\n\n**NOTE**: you should ensure users connect to your server through SSL.\n\nTo use it, ensure you have a GraphQL type called `User` in your schema, with a field `email`, by which users will be looked up. When creating users, ensure that a bcrypted `hash` database field is set. For instance, if you created your users in this way:\n\n```graphql\ntype User {\n  email: String!\n  bio: String\n}\n```\n\nYou could update the generated `CreateUserInput` input object to take a `password` field:\n\n```graphql\ninput CreateUserInput {\n  email: String!\n  password: String! # \u003c- you need to add this line to the generated output\n  bio: String\n}\n```\n\nAnd then update the generated `User` model to hash that password and store it:\n\n```js\nimport bcrypt from 'bcrypt';\n// Set this as appropriate\nconst SALT_ROUNDS = 10;\n\nclass User {\n  async insert(doc) {\n    // We don't want to store passwords plaintext!\n    const { password, ...rest } = doc;\n    const hash = await bcrypt.hash(password, SALT_ROUNDS);\n    const docToInsert = Object.assign({}, rest, {\n      hash,\n      createdAt: Date.now(),\n      updatedAt: Date.now(),\n    });\n\n    // This code is unchanged.\n    const id = (await this.collection.insertOne(docToInsert)).insertedId;\n    this.pubsub.publish('userInserted', await this.findOneById(id));\n    return id;\n  }\n}\n```\n\n### Client side code\n\nTo create users, simply call your generated `createUser` mutation (you may want to add authorization to the resolver, feel free to modify it).\n\nTo login on the client, you make a RESTful request to `/login` on the server, passing `email` and `password` in JSON. You'll get a JWT token back, which you should attach to the `Authorization` header of all GraphQL requests.\n\nHere's some code to do just that:\n\n```js\nconst KEY = 'authToken';\nlet token = localStorage.getItem(KEY);\n\nconst networkInterface = createNetworkInterface(/* as usual */);\nnetworkInterface.use([\n  {\n    applyMiddleware(req, next) {\n      req.options.headers = {\n        authorization: token ? `JWT ${token}` : null,\n        ...req.options.headers,\n      };\n      next();\n    },\n  },\n]);\n\n// Create your client as usual and pass to a provider\nconst client = /*...*/\n\n// Call this function from your login form, or wherever.\nconst login = async function(serverUrl, email, password) {\n  const response = await fetch(`${serverUrl}/login`, {\n    method: 'POST',\n    body: JSON.stringify({ email, password }),\n    headers: { 'Content-Type': 'application/json' },\n  });\n  const data = await response.json();\n  token = data.token;\n  localStorage.setItem(KEY, token);\n}\n```\n\n## Development\n\n### Running code generation tests\n\nYou can run some basic code generation tests with `npm test`.\n\n### Testing full app code generation\n\nA simple test to check that using the `test/input` input files with the CGS scripts generates `test/output-app` can be run with `npm run output-app-generation-test`.\n\n### Running end-to-end tests\n\nYou can run a set of end-to-end tests of the user/tweet app (which lives in `test/output-app`) with `npm run end-to-end-test`. This will seed the database, and run against a running server.\n\nThe test files are in `test/output-app-end-to-end`.\n\nYou need to start the standard server with `cd test/output-app; npm start`, then run `npm run end-to-end-test`.\n\n\n### Creating seed database\n\nIf you need to change the fixtures for the test db\n\nStart the server, then run\n```bash\nmongoexport --host 127.0.0.1:3002 --db database --collection user \u003e seeds/User.json\nmongoexport --host 127.0.0.1:3002 --db database --collection tweet \u003e seeds/Tweet.json\n```\n\n## Maintenance\n\nAs this is a code generator, and not a library, once you run the code, you are on your own :)\n\nBy 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.\n\nIf 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftmeasday%2Fcreate-graphql-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftmeasday%2Fcreate-graphql-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftmeasday%2Fcreate-graphql-server/lists"}