GraphQL+MogoDBexpressserver(iTypescript)
ThisisjustastarterexampleohowtobuildaGraphQLserverwithMogoDBdatabaseiTypescript.
Theadvaageofthissolutioisastrogtypecheckig,thakstoTypescript,adaeasyGraphQLschemadefiitiousigGraphQLSchemaadGraphQLObjectType.
Thelogicforthedatabasemodelsareisidethesrc/dbfolderwhilefortheGraphQLtypes,queryadmutatioareisidethesrc/schemafolder.Theschemaisthebuiltithesrc/schema/idex.tsfile.
FortheautheticatiothemethodsetupPassportAuthithefilesrc/autheticatio.tswillhadlealltheroutesadaccesstotheusertable.
MoredetailsUsigExpressadGraphQLHTTPServertosetupagraphqlserver.UsigPassportadPassportJSONWebTokeforuserautheticatiowithbcryptforhashigthepassworddurigusercreatio.UsigMogoosetoiteractwithMogoDBadtakeadvatageofeasymodeldefiitiosadsupportforTypescript.UsigGraphQL.jsdyamicallycreateaGraphQLSchemawithtypes,queryadmutatio.UsigTypescripttypecheckigcompilatiofordevelopmetadproductio.IstallThemaiExpressAppetrypoitissrc/server.ts,itcabelauchwiththefollowigcommads:
Fordevelopmet(withlivereload)
pmstartForproductio(appservedfromdistfolder)
pmrubuildUsageIthisexampleweopeaMogoDBcoectioomogodb://localhost:27017adopetheherosdatabase,soweeedtomakesuremogodserviceisruigadthedefaultportissetto27017(oryoucaadjusttheparametersithesrc/server.tsfile).
Rutheexpressserver(withpmstartorpmbuild).
Weeedthetocreateausertologiwith,wecacreateaadmiuserbyvisitigthedebugurlhttps://localhost:3000/add-admi-user.
Wecathelogifromtheauthformbyvisitighttps://localhost:3000/auth(defaultuserame:admi,password:admi).
Thelogipagewillrespodwithaauthtoke,ifyouuseaclietwecasaveitadsetititheheadersforthefollowigrequests,ifyouuseaBrowseryoucauseaextesio(likethisforChrome)tosettheAuthorizatioheaderwiththetoke(thetokeeedtobeprecededbyJWTlikeJWTeyJhbGcixxxxxxxxx.
NowyouarereadytoopetheGraphQLispectorbyvisitighttps://localhost:3000/graphqladbrowsetheschemaaddoquery,mutatio,etc.
LiceseMIT







评论