CreateGraphQLServer
Create-graphql-serverisascaffoldigtoolthatletsyougeerateaewMogo/Express/Node.jsGraphQLserverprojectfromthecommadlie.AftergeeratigtheprojectyoucaalsogeeratecodetosupportyourGraphQLschemadirectlyfromtheschemafiles.BasicautheticatiosupportisicludedviaPassportLocalwithJWTs.
NOTE:thisprojectisotactivelymaitaied.Asascaffoldigtool,thisisotecessarilyaissue(youcageerateaprojectwithitadtheforgetaboutthetool),butitisicreasiglyfalligoutofdate.Aspritiualsuccessoristhegraphql-cliproject.Pleasetakealook!
GettigStartedIstallatioIstallitoceglobally:
pmistall-gcreate-graphql-serverCreatigaServerTocreateaewserverithemy-ew-server-dirfolderusetheiitcommad:
create-graphql-serveriitmy-ew-server-dircdmy-ew-server-diryaristallStartigtheServerImostdevelopmetevirometsyoucaowfireupyourewserverusigthepackagedprebuiltMogoserver:
yarstartIfmogo-prebuiltfailstostart,oryou'dratheruseaotherMogoDBistallatiofordevelopmet,simplysettheMONGO_URLevirometvariablewheyoustarttheserver,asfollows:
#OWidows:SETMONGO_URL=mogodb://localhost:27017&&yarstart#OUix/OSX:MONGO_URL=mogodb://localhost:27017yarstartIfyousetupauserame,passwordoradifferetportforMogo,orareaccessigMogothroughaservicesuchasmLab,correcttheMONGO_URLabovetoreflectthat.
RuigQueriesYourserverisowupadruig.Toqueryit,poityourbrowserathttps://localhost:3010/graphiql.Thereis'taythigtoqueryyethowever.
AddigTypes:OverviewToaddtypes,youcadefiethemiGraphQLschemafiles,thegeeratecodeforthemusigtheadd-typecommad,asfollows:
create-graphql-serveradd-typepath/to/my-ew-type.graphqlIfyouhaveafolderfullofschemafiles,youcaaddthemallatocebypoitigadd-typetoafolderisteadofaidividualschemafile:
create-graphql-serveradd-typepathSampleschemafilesareicludeditest/iput.Toseewhatacompletegeeratedserverlookslikeusigthem,checkouttest/output-app.
SchemasYoucreateaGraphQLtypeforyourschemabyspecifyigthetypeasiput,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).RelatiosIftypesrefereceeachother,youshoulduseaassociatiodirectivetoexplaitothegeeratorhowtherefereceshouldbestoredimogo:
SigletofieldsIfthefieldreferecesasigle(ullableorotherwise)istaceofaothertype,itwillbeeither:
@belogsTo-theforeigkeyisstoredothistypeas${fieldName}Id[thisisthedefault]@hasOe-theforeigkeyisstoredothereferecedtypeas${typeName}Id.Providethe"as":Xargumetiftheameisdifferet.[NOTE:thisisotyetfullyimplemeted].PagiatedfieldsIfthefieldreferecesaarray(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).UpdatigtypesToupdatetypes,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.
RemovigtypesToremovetypes,usethefollowigcommadwiththepathtotheGraphQLfile,orasalterative,justeterthetypeamewithoutpath.
create-graphql-serverremove-typepath/to/iput.graphqlcreate-graphql-serverremove-typetypeamecreate-graphql-serverremove-typepathThiscommaddeletesyouroldtypespecificfilesfromthedirectories:schema,model,resolvers.Italsoremovesthecodereferecesoutofthecorrespodigidexfiles.
Itrecogizes,ifyou'vechagedaycodefile,whichwillbeoverwrittebythegeeratoradstopsadwars.Ifyouaresure,youwattooverwriteyourchages,thejustusetheforce-updateoptio.
AutheticatioCGSsetsupabasicpassport-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;}}ClietsidecodeTocreateusers,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);}DevelopmetRuigcodegeeratiotestsYoucarusomebasiccodegeeratiotestswithpmtest.
TestigfullappcodegeeratioAsimpletesttocheckthatusigthetest/iputiputfileswiththeCGSscriptsgeeratestest/output-appcaberuwithpmruoutput-app-geeratio-test.
Ruiged-to-edtestsYoucaruasetofed-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.
CreatigseeddatabaseIfyoueedtochagethefixturesforthetestdb
Starttheserver,theru
mogoexport--host127.0.0.1:3002--dbdatabase--collectiouser>seeds/User.jsomogoexport--host127.0.0.1:3002--dbdatabase--collectiotweet>seeds/Tweet.jsoMaiteaceAsthisisacodegeerator,adotalibrary,oceyouruthecode,youareoyourow:)
BywhichImea,youshouldfeelfreetoreadthegeeratedcode,uderstadit,admodifyitasyouseefit.AyupdatestoCGSwilljustaffectfutureappsthatyougeerate.
Ifyou'dliketoseeimprovemets,orfidaybugs,byallmeasreportthemviatheissues,adsedPRs.Butworkaroudsshouldbealwaysbepossiblesimplybypatchigthegeeratedcode.







评论