create-graphql-server Generate your GraphQL server开源项目

我要开发同款
匿名用户2021年11月23日
93阅读

技术信息

开源地址
https://gitee.com/MTrun/react-big-screen
授权协议
MIT License

作品详情

CreateGraphQLServer

Create-graphql-serverisascaffoldigtoolthatletsyougeerateaewMogo/Express/Node.jsGraphQLserverprojectfromthecommadlie.AftergeeratigtheprojectyoucaalsogeeratecodetosupportyourGraphQLschemadirectlyfromtheschemafiles.BasicautheticatiosupportisicludedviaPassportLocalwithJWTs.

NOTE:thisprojectisotactivelymaitaied.Asascaffoldigtool,thisisotecessarilyaissue(youcageerateaprojectwithitadtheforgetaboutthetool),butitisicreasiglyfalligoutofdate.Aspritiualsuccessoristhegraphql-cliproject.Pleasetakealook!

GettigStartedIstallatio

Istallitoceglobally:

pmistall-gcreate-graphql-serverCreatigaServer

Tocreateaewserverithemy-ew-server-dirfolderusetheiitcommad:

create-graphql-serveriitmy-ew-server-dircdmy-ew-server-diryaristallStartigtheServer

ImostdevelopmetevirometsyoucaowfireupyourewserverusigthepackagedprebuiltMogoserver:

yarstart

Ifmogo-prebuiltfailstostart,oryou'dratheruseaotherMogoDBistallatiofordevelopmet,simplysettheMONGO_URLevirometvariablewheyoustarttheserver,asfollows:

#OWidows:SETMONGO_URL=mogodb://localhost:27017&&yarstart#OUix/OSX:MONGO_URL=mogodb://localhost:27017yarstart

Ifyousetupauserame,passwordoradifferetportforMogo,orareaccessigMogothroughaservicesuchasmLab,correcttheMONGO_URLabovetoreflectthat.

RuigQueries

Yourserverisowupadruig.Toqueryit,poityourbrowserathttps://localhost:3010/graphiql.Thereis'taythigtoqueryyethowever.

AddigTypes:Overview

Toaddtypes,youcadefiethemiGraphQLschemafiles,thegeeratecodeforthemusigtheadd-typecommad,asfollows:

create-graphql-serveradd-typepath/to/my-ew-type.graphql

Ifyouhaveafolderfullofschemafiles,youcaaddthemallatocebypoitigadd-typetoafolderisteadofaidividualschemafile:

create-graphql-serveradd-typepath

Sampleschemafilesareicludeditest/iput.Toseewhatacompletegeeratedserverlookslikeusigthem,checkouttest/output-app.

Schemas

YoucreateaGraphQLtypeforyourschemabyspecifyigthetypeasiput,withsomespecialcode-geeratiocotrolligdirectives.

Forexample,iUser.graphql:

typeUser{email:Strig!bio:Strigtweets:[Tweet!]@hasMay(as:"author")liked:[Tweet!]@belogsToMayfollowig:[User!]@belogsToMayfollowers:[User!]@hasAdBelogsToMay(as:"followig")}

TheabovewillgeerateaUsertypewhichislikedtootherusersadatweettypeviaforiegkeysadwhichwillhavemutatiostoadd,updateadremoveusers,aswellassomerootqueriestofidasigleuserorallusers.

Thedirectivesusedcotrolthecodegeeratio(seebelow).

Directives@umodifiable-thefieldwillotappearitheupdatemutatio@eum-thefield'stypeisaeum,adcabesetdirectly(otjustbyId).Relatios

Iftypesrefereceeachother,youshoulduseaassociatiodirectivetoexplaitothegeeratorhowtherefereceshouldbestoredimogo:

Sigletofields

Ifthefieldreferecesasigle(ullableorotherwise)istaceofaothertype,itwillbeeither:

@belogsTo-theforeigkeyisstoredothistypeas${fieldName}Id[thisisthedefault]@hasOe-theforeigkeyisstoredothereferecedtypeas${typeName}Id.Providethe"as":Xargumetiftheameisdifferet.[NOTE:thisisotyetfullyimplemeted].Pagiatedfields

Ifthefieldreferecesaarray(agaiw/orw/oullability)ofaothertype,itwillbeeither:

@belogsToMay-thereisalistofforeigkeysstoredothistypeas${fieldName}Ids[thisisthedefault]@hasMay-theforeigkeyisothereferecedtypeas${typeName}Id.Providethe"as":Xargumetiftheameisdifferet.(thisisthereverseof@belogsToia1-maysituatio).@hasAdBelogsToMay-theforeigkeyothereferecedtypeas${typeName}Ids.Providethe"as":Xargumetiftheameisdifferet.(thisisthereverseof@belogsToMayiamay-maysituatio).Updatigtypes

Toupdatetypes,justre-ruadd-typeagai:

create-graphql-serveradd-typepath/to/iput.graphql[--force-update]

Thisoverwritesyouroldtypespecificfilesfromthedirectories:schema,model,resolvers.

Itrecogizes,ifyou'vechagedaycodefile,whichwillbeoverwrittebythegeeratoradstopsadwars.Ifyouaresure,youwattooverwriteyourchages,thejustusethe--force-updateoptio.

Removigtypes

Toremovetypes,usethefollowigcommadwiththepathtotheGraphQLfile,orasalterative,justeterthetypeamewithoutpath.

create-graphql-serverremove-typepath/to/iput.graphqlcreate-graphql-serverremove-typetypeamecreate-graphql-serverremove-typepath

Thiscommaddeletesyouroldtypespecificfilesfromthedirectories:schema,model,resolvers.Italsoremovesthecodereferecesoutofthecorrespodigidexfiles.

Itrecogizes,ifyou'vechagedaycodefile,whichwillbeoverwrittebythegeeratoradstopsadwars.Ifyouaresure,youwattooverwriteyourchages,thejustusetheforce-updateoptio.

Autheticatio

CGSsetsupabasicpassport-basedJWTautheticatiosystemforyourapp.

NOTE:youshouldesureuserscoecttoyourserverthroughSSL.

Touseit,esureyouhaveaGraphQLtypecalledUseriyourschema,withafieldemail,bywhichuserswillbelookedup.Whecreatigusers,esurethatabcryptedhashdatabasefieldisset.Foristace,ifyoucreatedyourusersithisway:

typeUser{email:Strig!bio:Strig}

YoucouldupdatethegeeratedCreateUserIputiputobjecttotakeapasswordfield:

iputCreateUserIput{email:Strig!password:Strig!#<-youeedtoaddthislietothegeeratedoutputbio:Strig}

AdtheupdatethegeeratedUsermodeltohashthatpasswordadstoreit:

importbcryptfrom'bcrypt';//SetthisasappropriatecostSALT_ROUNDS=10;classUser{asycisert(doc){//Wedo'twattostorepasswordsplaitext!cost{password,...rest}=doc;costhash=awaitbcrypt.hash(password,SALT_ROUNDS);costdocToIsert=Object.assig({},rest,{hash,createdAt:Date.ow(),updatedAt:Date.ow(),});//Thiscodeisuchaged.costid=(awaitthis.collectio.isertOe(docToIsert)).isertedId;this.pubsub.publish('userIserted',awaitthis.fidOeById(id));returid;}}Clietsidecode

Tocreateusers,simplycallyourgeeratedcreateUsermutatio(youmaywattoaddauthorizatiototheresolver,feelfreetomodifyit).

Tologiothecliet,youmakeaRESTfulrequestto/logiotheserver,passigemailadpasswordiJSON.You'llgetaJWTtokeback,whichyoushouldattachtotheAuthorizatioheaderofallGraphQLrequests.

Here'ssomecodetodojustthat:

costKEY='authToke';lettoke=localStorage.getItem(KEY);costetworkIterface=createNetworkIterface(/*asusual*/);etworkIterface.use([{applyMiddleware(req,ext){req.optios.headers={authorizatio:toke?`JWT${toke}`:ull,...req.optios.headers,};ext();},},]);//Createyourclietasusualadpasstoaprovidercostcliet=/*...*///Callthisfuctiofromyourlogiform,orwherever.costlogi=asycfuctio(serverUrl,email,password){costrespose=awaitfetch(`${serverUrl}/logi`,{method:'POST',body:JSON.strigify({email,password}),headers:{'Cotet-Type':'applicatio/jso'},});costdata=awaitrespose.jso();toke=data.toke;localStorage.setItem(KEY,toke);}DevelopmetRuigcodegeeratiotests

Youcarusomebasiccodegeeratiotestswithpmtest.

Testigfullappcodegeeratio

Asimpletesttocheckthatusigthetest/iputiputfileswiththeCGSscriptsgeeratestest/output-appcaberuwithpmruoutput-app-geeratio-test.

Ruiged-to-edtests

Youcaruasetofed-to-edtestsoftheuser/tweetapp(whichlivesitest/output-app)withpmrued-to-ed-test.Thiswillseedthedatabase,adruagaistaruigserver.

Thetestfilesareitest/output-app-ed-to-ed.

Youeedtostartthestadardserverwithcdtest/output-app;pmstart,therupmrued-to-ed-test.

Creatigseeddatabase

Ifyoueedtochagethefixturesforthetestdb

Starttheserver,theru

mogoexport--host127.0.0.1:3002--dbdatabase--collectiouser>seeds/User.jsomogoexport--host127.0.0.1:3002--dbdatabase--collectiotweet>seeds/Tweet.jsoMaiteace

Asthisisacodegeerator,adotalibrary,oceyouruthecode,youareoyourow:)

BywhichImea,youshouldfeelfreetoreadthegeeratedcode,uderstadit,admodifyitasyouseefit.AyupdatestoCGSwilljustaffectfutureappsthatyougeerate.

Ifyou'dliketoseeimprovemets,orfidaybugs,byallmeasreportthemviatheissues,adsedPRs.Butworkaroudsshouldbealwaysbepossiblesimplybypatchigthegeeratedcode.

功能介绍

Create GraphQL Server Create-graphql-server is a scaffolding tool that lets you generate a new Mo...

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论