ThisisjustastarterexampleonhowtobuildaGraphQLserverwithMongoDBdatabaseinTypescript.
Theadvanageofthissolutionisastrongtypechecking,thankstoTypescript,andaeasyGraphQLschemadefinitionusingGraphQLSchemaandGraphQLObjectType.
Thelogicforthedatabasemodelsareinsidethesrc/dbfolderwhilefortheGraphQLtypes,queryandmutationareinsidethesrc/schemafolder.Theschemaisthenbuiltinthesrc/schema/index.tsfile.
FortheautheticationthemethodsetupPassportAuthinthefilesrc/authetication.tswillhandlealltheroutesandaccesstotheusertable.
MoredetailsUsingExpressandGraphQLHTTPServertosetupagraphqlserver.UsingPassportandPassportJSONWebTokenforuserauthenticationwithbcryptforhashingthepasswordduringusercreation.UsingMongoosetointeractwithMongoDBandtakeadvantageofeasymodeldefinitionsandsupportforTypescript.UsingGraphQL.jsdynamicallycreateaGraphQLSchemawithtypes,queryandmutation.UsingTypescripttypecheckingcompilationfordevelopmentandproduction.InstallThemainExpressAppentrypointissrc/server.ts,itcanbelaunchwiththefollowingcommands:
Fordevelopment(withlivereload)
npmstartForproduction(appservedfromdistfolder)
npmrunbuildUsageInthisexampleweopenaMongoDBconnectiononmongodb://localhost:27017andopentheherosdatabase,soweneedtomakesuremongodserviceisrunningandthedefaultportissetto27017(oryoucanadjusttheparametersinthesrc/server.tsfile).
Runtheexpressserver(withnpmstartornpmbuild).
Weneedthentocreateausertologinwith,wecancreateanadminuserbyvisitingthedebugurlhttps://localhost:3000/add-admin-user.
Wecanthenloginfromtheauthformbyvisitinghttps://localhost:3000/auth(defaultusername:admin,password:admin).
Theloginpagewillrespondwithanauthtoken,ifyouuseaclientwecansaveitandsetitintheheadersforthefollowingrequests,ifyouuseaBrowseryoucanuseanextension(likethisforChrome)tosettheAuthorizationheaderwiththetoken(thetokenneedtobeprecededbyJWTlikeJWTeyJhbGcixxxxxxxxx.
NowyouarereadytoopentheGraphQLinspectorbyvisitinghttps://localhost:3000/graphqlandbrowsetheschemaanddoquery,mutation,etc.
LicenseMIT
评论