some cleanup and gqlgen setup

This commit is contained in:
Ankit Patial 2024-11-01 19:55:30 +05:30
parent e41d27cf97
commit 1fb2d7d154
39 changed files with 5619 additions and 144 deletions

3
.gitignore vendored
View File

@ -20,3 +20,6 @@ Thumbs.db
# Vite # Vite
vite.config.js.timestamp-* vite.config.js.timestamp-*
vite.config.ts.timestamp-* vite.config.ts.timestamp-*
# Houdini
$houdini

9
.graphqlrc.yaml Normal file
View File

@ -0,0 +1,9 @@
projects:
default:
schema:
- ./graph/*.graphql
- ./$houdini/graphql/schema.graphql
documents:
- './web/**/*.gql'
- './web/**/*.svelte'
- ./$houdini/graphql/documents.gql

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

18
.prettierrc Normal file
View File

@ -0,0 +1,18 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 120,
"plugins": [
"prettier-plugin-svelte",
"prettier-plugin-tailwindcss"
],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
]
}

View File

@ -1,38 +1,11 @@
# create-svelte # RANO
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte). "Reliable And Nonstop Operations" for
## Creating a project ## Prerequisites
If you're seeing this, you've probably already done this step. Congrats! - [deno](https://docs.deno.com/runtime/) to manage node modules
- [go-task](https://taskfile.dev/installation/) to run tasks
```bash ```bash
# create a new project in the current directory go install github.com/go-task/task/v3/cmd/task@latest
npm create svelte@latest ```
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

View File

@ -1 +0,0 @@
!#/bin/sh

View File

@ -1,2 +0,0 @@
!#/bin/sh
deno task dev

1268
deno.lock

File diff suppressed because it is too large Load Diff

3
eslint.config.js Normal file
View File

@ -0,0 +1,3 @@
import prettier from 'eslint-config-prettier';
import svelte from 'eslint-plugin-svelte';
export default [prettier, ...svelte.configs['flat/prettier']];

25
go.mod
View File

@ -2,4 +2,27 @@ module gitserver.in/patialtech/rano
go 1.23.2 go 1.23.2
require gitserver.in/patialtech/mux v0.0.3 require (
github.com/99designs/gqlgen v0.17.55
github.com/vektah/gqlparser v1.3.1
github.com/vektah/gqlparser/v2 v2.5.18
gitserver.in/patialtech/mux v0.0.3
)
require (
github.com/agnivade/levenshtein v1.1.1 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sosodev/duration v1.3.1 // indirect
github.com/urfave/cli/v2 v2.27.4 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/text v0.18.0 // indirect
golang.org/x/tools v0.24.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

69
go.sum
View File

@ -1,2 +1,71 @@
github.com/99designs/gqlgen v0.17.55 h1:3vzrNWYyzSZjGDFo68e5j9sSauLxfKvLp+6ioRokVtM=
github.com/99designs/gqlgen v0.17.55/go.mod h1:3Bq768f8hgVPGZxL8aY9MaYmbxa6llPM/qu1IGH1EJo=
github.com/PuerkitoBio/goquery v1.9.3 h1:mpJr/ikUA9/GNJB/DBZcGeFDXUtosHRyRrwh7KGdTG0=
github.com/PuerkitoBio/goquery v1.9.3/go.mod h1:1ndLHPdTz+DyQPICCWYlYQMPl0oXZj0G6D4LCYA6u4U=
github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM=
github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8=
github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo=
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g=
github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/sosodev/duration v1.3.1 h1:qtHBDMQ6lvMQsL15g4aopM4HEfOaYuhWBw3NPTtlqq4=
github.com/sosodev/duration v1.3.1/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/urfave/cli/v2 v2.27.4 h1:o1owoI+02Eb+K107p27wEX9Bb8eqIoZCfLXloLUSWJ8=
github.com/urfave/cli/v2 v2.27.4/go.mod h1:m4QzxcD2qpra4z7WhzEGn74WZLViBnMpb1ToCAKdGRQ=
github.com/vektah/gqlparser v1.3.1 h1:8b0IcD3qZKWJQHSzynbDlrtP3IxVydZ2DZepCGofqfU=
github.com/vektah/gqlparser v1.3.1/go.mod h1:bkVf0FX+Stjg/MHnm8mEyubuaArhNEqfQhF+OTiAL74=
github.com/vektah/gqlparser/v2 v2.5.17 h1:9At7WblLV7/36nulgekUgIaqHZWn5hxqluxrxGUhOmI=
github.com/vektah/gqlparser/v2 v2.5.17/go.mod h1:1lz1OeCqgQbQepsGxPVywrjdBHW2T08PUS3pJqepRww=
github.com/vektah/gqlparser/v2 v2.5.18 h1:zSND3GtutylAQ1JpWnTHcqtaRZjl+y3NROeW8vuNo6Y=
github.com/vektah/gqlparser/v2 v2.5.18/go.mod h1:6HLzf7JKv9Fi3APymudztFQNmLXR5qJeEo6BOFcXVfc=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
gitserver.in/patialtech/mux v0.0.3 h1:Td0nAqArLGjB2pAVatEX2/pKaNqHvj4jqLD+PJHobxc= gitserver.in/patialtech/mux v0.0.3 h1:Td0nAqArLGjB2pAVatEX2/pKaNqHvj4jqLD+PJHobxc=
gitserver.in/patialtech/mux v0.0.3/go.mod h1:/pYaLBNkRiMuxMKn9e2X0BIWt1bvHM19yQE/cJsm0q0= gitserver.in/patialtech/mux v0.0.3/go.mod h1:/pYaLBNkRiMuxMKn9e2X0BIWt1bvHM19yQE/cJsm0q0=
golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0=
golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

98
gqlgen.yml Normal file
View File

@ -0,0 +1,98 @@
# Where are all the schema files located? globs are supported eg src/**/*.graphqls
schema:
- graph/*.graphql
# Where should the generated server code go?
exec:
layout: follow-schema
dir: graph/generated
package: generated
# Uncomment to enable federation
# federation:
# filename: graph/federation.go
# package: graph
# version: 2
# options
# computed_requires: true
# Where should any generated models go?
model:
filename: graph/model/models_gen.go
package: model
# Where should the resolver implementations go?
resolver:
layout: follow-schema
dir: graph
package: graph
filename_template: '{name}.resolvers.go'
# Optional: turn on to not generate template comments above resolvers
# omit_template_comment: false
# Optional: turn on use ` + "`" + `gqlgen:"fieldName"` + "`" + ` tags in your models
# struct_tag: json
# Optional: turn on to use []Thing instead of []*Thing
# omit_slice_element_pointers: false
# Optional: turn on to omit Is<Name>() methods to interface and unions
# omit_interface_checks : true
# Optional: turn on to skip generation of ComplexityRoot struct content and Complexity function
# omit_complexity: false
# Optional: turn on to not generate any file notice comments in generated files
# omit_gqlgen_file_notice: false
# Optional: turn on to exclude the gqlgen version in the generated file notice. No effect if `omit_gqlgen_file_notice` is true.
# omit_gqlgen_version_in_file_notice: false
# Optional: turn off to make struct-type struct fields not use pointers
# e.g. type Thing struct { FieldA OtherThing } instead of { FieldA *OtherThing }
# struct_fields_always_pointers: true
# Optional: turn off to make resolvers return values instead of pointers for structs
# resolvers_always_return_pointers: true
# Optional: turn on to return pointers instead of values in unmarshalInput
# return_pointers_in_unmarshalinput: false
# Optional: wrap nullable input fields with Omittable
# nullable_input_omittable: true
# Optional: set to speed up generation time by not performing a final validation pass.
# skip_validation: true
# Optional: set to skip running `go mod tidy` when generating server code
# skip_mod_tidy: true
# Optional: if this is set to true, argument directives that
# decorate a field with a null value will still be called.
#
# This enables argumment directives to not just mutate
# argument values but to set them even if they're null.
call_argument_directives_with_null: true
# gqlgen will search for any type names in the schema in these go packages
# if they match it will use them, otherwise it will generate them.
autobind:
- 'gitserver.in/patialtech/rano/graph/model'
# This section declares type mapping between the GraphQL and go type systems
#
# The first line in each type will be used as defaults for resolver arguments and
# modelgen, the others will be allowed when binding to fields. Configure them to
# your liking
models:
ID:
model:
- github.com/99designs/gqlgen/graphql.ID
- github.com/99designs/gqlgen/graphql.Int
- github.com/99designs/gqlgen/graphql.Int64
- github.com/99designs/gqlgen/graphql.Int32
Int:
model:
- github.com/99designs/gqlgen/graphql.Int
- github.com/99designs/gqlgen/graphql.Int64
- github.com/99designs/gqlgen/graphql.Int32

4
graph/auth.graphql Normal file
View File

@ -0,0 +1,4 @@
extend type Mutation {
login(username: String!, email: String!): Boolean!
logout: Boolean!
}

20
graph/auth.resolvers.go Normal file
View File

@ -0,0 +1,20 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.55
import (
"context"
"fmt"
)
// Login is the resolver for the login field.
func (r *mutationResolver) Login(ctx context.Context, username string, email string) (bool, error) {
panic(fmt.Errorf("not implemented: Login - login"))
}
// Logout is the resolver for the logout field.
func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
panic(fmt.Errorf("not implemented: Logout - logout"))
}

View File

@ -0,0 +1,519 @@
// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.
package generated
import (
"context"
"errors"
"fmt"
"strconv"
"sync/atomic"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/introspection"
"github.com/vektah/gqlparser/v2/ast"
)
// region ************************** generated!.gotpl **************************
type MutationResolver interface {
Login(ctx context.Context, username string, email string) (bool, error)
Logout(ctx context.Context) (bool, error)
}
type QueryResolver interface {
HeartBeat(ctx context.Context) (bool, error)
}
// endregion ************************** generated!.gotpl **************************
// region ***************************** args.gotpl *****************************
func (ec *executionContext) field_Mutation_login_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
var err error
args := map[string]interface{}{}
arg0, err := ec.field_Mutation_login_argsUsername(ctx, rawArgs)
if err != nil {
return nil, err
}
args["username"] = arg0
arg1, err := ec.field_Mutation_login_argsEmail(ctx, rawArgs)
if err != nil {
return nil, err
}
args["email"] = arg1
return args, nil
}
func (ec *executionContext) field_Mutation_login_argsUsername(
ctx context.Context,
rawArgs map[string]interface{},
) (string, error) {
ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("username"))
if tmp, ok := rawArgs["username"]; ok {
return ec.unmarshalNString2string(ctx, tmp)
}
var zeroVal string
return zeroVal, nil
}
func (ec *executionContext) field_Mutation_login_argsEmail(
ctx context.Context,
rawArgs map[string]interface{},
) (string, error) {
ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("email"))
if tmp, ok := rawArgs["email"]; ok {
return ec.unmarshalNString2string(ctx, tmp)
}
var zeroVal string
return zeroVal, nil
}
func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
var err error
args := map[string]interface{}{}
arg0, err := ec.field_Query___type_argsName(ctx, rawArgs)
if err != nil {
return nil, err
}
args["name"] = arg0
return args, nil
}
func (ec *executionContext) field_Query___type_argsName(
ctx context.Context,
rawArgs map[string]interface{},
) (string, error) {
ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("name"))
if tmp, ok := rawArgs["name"]; ok {
return ec.unmarshalNString2string(ctx, tmp)
}
var zeroVal string
return zeroVal, nil
}
// endregion ***************************** args.gotpl *****************************
// region ************************** directives.gotpl **************************
// endregion ************************** directives.gotpl **************************
// region **************************** field.gotpl *****************************
func (ec *executionContext) _Mutation_login(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Mutation_login(ctx, field)
if err != nil {
return graphql.Null
}
ctx = graphql.WithFieldContext(ctx, fc)
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
ret = graphql.Null
}
}()
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return ec.resolvers.Mutation().Login(rctx, fc.Args["username"].(string), fc.Args["email"].(string))
})
if err != nil {
ec.Error(ctx, err)
return graphql.Null
}
if resTmp == nil {
if !graphql.HasFieldError(ctx, fc) {
ec.Errorf(ctx, "must not be null")
}
return graphql.Null
}
res := resTmp.(bool)
fc.Result = res
return ec.marshalNBoolean2bool(ctx, field.Selections, res)
}
func (ec *executionContext) fieldContext_Mutation_login(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Mutation",
Field: field,
IsMethod: true,
IsResolver: true,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return nil, errors.New("field of type Boolean does not have child fields")
},
}
defer func() {
if r := recover(); r != nil {
err = ec.Recover(ctx, r)
ec.Error(ctx, err)
}
}()
ctx = graphql.WithFieldContext(ctx, fc)
if fc.Args, err = ec.field_Mutation_login_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {
ec.Error(ctx, err)
return fc, err
}
return fc, nil
}
func (ec *executionContext) _Mutation_logout(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Mutation_logout(ctx, field)
if err != nil {
return graphql.Null
}
ctx = graphql.WithFieldContext(ctx, fc)
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
ret = graphql.Null
}
}()
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return ec.resolvers.Mutation().Logout(rctx)
})
if err != nil {
ec.Error(ctx, err)
return graphql.Null
}
if resTmp == nil {
if !graphql.HasFieldError(ctx, fc) {
ec.Errorf(ctx, "must not be null")
}
return graphql.Null
}
res := resTmp.(bool)
fc.Result = res
return ec.marshalNBoolean2bool(ctx, field.Selections, res)
}
func (ec *executionContext) fieldContext_Mutation_logout(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Mutation",
Field: field,
IsMethod: true,
IsResolver: true,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return nil, errors.New("field of type Boolean does not have child fields")
},
}
return fc, nil
}
func (ec *executionContext) _Query_heartBeat(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Query_heartBeat(ctx, field)
if err != nil {
return graphql.Null
}
ctx = graphql.WithFieldContext(ctx, fc)
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
ret = graphql.Null
}
}()
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return ec.resolvers.Query().HeartBeat(rctx)
})
if err != nil {
ec.Error(ctx, err)
return graphql.Null
}
if resTmp == nil {
if !graphql.HasFieldError(ctx, fc) {
ec.Errorf(ctx, "must not be null")
}
return graphql.Null
}
res := resTmp.(bool)
fc.Result = res
return ec.marshalNBoolean2bool(ctx, field.Selections, res)
}
func (ec *executionContext) fieldContext_Query_heartBeat(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Query",
Field: field,
IsMethod: true,
IsResolver: true,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return nil, errors.New("field of type Boolean does not have child fields")
},
}
return fc, nil
}
func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Query___type(ctx, field)
if err != nil {
return graphql.Null
}
ctx = graphql.WithFieldContext(ctx, fc)
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
ret = graphql.Null
}
}()
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return ec.introspectType(fc.Args["name"].(string))
})
if err != nil {
ec.Error(ctx, err)
return graphql.Null
}
if resTmp == nil {
return graphql.Null
}
res := resTmp.(*introspection.Type)
fc.Result = res
return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res)
}
func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Query",
Field: field,
IsMethod: true,
IsResolver: false,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
switch field.Name {
case "kind":
return ec.fieldContext___Type_kind(ctx, field)
case "name":
return ec.fieldContext___Type_name(ctx, field)
case "description":
return ec.fieldContext___Type_description(ctx, field)
case "fields":
return ec.fieldContext___Type_fields(ctx, field)
case "interfaces":
return ec.fieldContext___Type_interfaces(ctx, field)
case "possibleTypes":
return ec.fieldContext___Type_possibleTypes(ctx, field)
case "enumValues":
return ec.fieldContext___Type_enumValues(ctx, field)
case "inputFields":
return ec.fieldContext___Type_inputFields(ctx, field)
case "ofType":
return ec.fieldContext___Type_ofType(ctx, field)
case "specifiedByURL":
return ec.fieldContext___Type_specifiedByURL(ctx, field)
}
return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name)
},
}
defer func() {
if r := recover(); r != nil {
err = ec.Recover(ctx, r)
ec.Error(ctx, err)
}
}()
ctx = graphql.WithFieldContext(ctx, fc)
if fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {
ec.Error(ctx, err)
return fc, err
}
return fc, nil
}
func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
fc, err := ec.fieldContext_Query___schema(ctx, field)
if err != nil {
return graphql.Null
}
ctx = graphql.WithFieldContext(ctx, fc)
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
ret = graphql.Null
}
}()
resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
ctx = rctx // use context from middleware stack in children
return ec.introspectSchema()
})
if err != nil {
ec.Error(ctx, err)
return graphql.Null
}
if resTmp == nil {
return graphql.Null
}
res := resTmp.(*introspection.Schema)
fc.Result = res
return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res)
}
func (ec *executionContext) fieldContext_Query___schema(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Query",
Field: field,
IsMethod: true,
IsResolver: false,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
switch field.Name {
case "description":
return ec.fieldContext___Schema_description(ctx, field)
case "types":
return ec.fieldContext___Schema_types(ctx, field)
case "queryType":
return ec.fieldContext___Schema_queryType(ctx, field)
case "mutationType":
return ec.fieldContext___Schema_mutationType(ctx, field)
case "subscriptionType":
return ec.fieldContext___Schema_subscriptionType(ctx, field)
case "directives":
return ec.fieldContext___Schema_directives(ctx, field)
}
return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name)
},
}
return fc, nil
}
// endregion **************************** field.gotpl *****************************
// region **************************** input.gotpl *****************************
// endregion **************************** input.gotpl *****************************
// region ************************** interface.gotpl ***************************
// endregion ************************** interface.gotpl ***************************
// region **************************** object.gotpl ****************************
var mutationImplementors = []string{"Mutation"}
func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler {
fields := graphql.CollectFields(ec.OperationContext, sel, mutationImplementors)
ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{
Object: "Mutation",
})
out := graphql.NewFieldSet(fields)
deferred := make(map[string]*graphql.FieldSet)
for i, field := range fields {
innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{
Object: field.Name,
Field: field,
})
switch field.Name {
case "__typename":
out.Values[i] = graphql.MarshalString("Mutation")
case "login":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_login(ctx, field)
})
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "logout":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_logout(ctx, field)
})
if out.Values[i] == graphql.Null {
out.Invalids++
}
default:
panic("unknown field " + strconv.Quote(field.Name))
}
}
out.Dispatch(ctx)
if out.Invalids > 0 {
return graphql.Null
}
atomic.AddInt32(&ec.deferred, int32(len(deferred)))
for label, dfs := range deferred {
ec.processDeferredGroup(graphql.DeferredGroup{
Label: label,
Path: graphql.GetPath(ctx),
FieldSet: dfs,
Context: ctx,
})
}
return out
}
var queryImplementors = []string{"Query"}
func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler {
fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors)
ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{
Object: "Query",
})
out := graphql.NewFieldSet(fields)
deferred := make(map[string]*graphql.FieldSet)
for i, field := range fields {
innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{
Object: field.Name,
Field: field,
})
switch field.Name {
case "__typename":
out.Values[i] = graphql.MarshalString("Query")
case "heartBeat":
field := field
innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
}
}()
res = ec._Query_heartBeat(ctx, field)
if res == graphql.Null {
atomic.AddUint32(&fs.Invalids, 1)
}
return res
}
rrm := func(ctx context.Context) graphql.Marshaler {
return ec.OperationContext.RootResolverMiddleware(ctx,
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
}
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
case "__type":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Query___type(ctx, field)
})
case "__schema":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Query___schema(ctx, field)
})
default:
panic("unknown field " + strconv.Quote(field.Name))
}
}
out.Dispatch(ctx)
if out.Invalids > 0 {
return graphql.Null
}
atomic.AddInt32(&ec.deferred, int32(len(deferred)))
for label, dfs := range deferred {
ec.processDeferredGroup(graphql.DeferredGroup{
Label: label,
Path: graphql.GetPath(ctx),
FieldSet: dfs,
Context: ctx,
})
}
return out
}
// endregion **************************** object.gotpl ****************************
// region ***************************** type.gotpl *****************************
// endregion ***************************** type.gotpl *****************************

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,261 @@
// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.
package generated
import (
"bytes"
"context"
"errors"
"sync/atomic"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/introspection"
gqlparser "github.com/vektah/gqlparser/v2"
"github.com/vektah/gqlparser/v2/ast"
)
// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface.
func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {
return &executableSchema{
schema: cfg.Schema,
resolvers: cfg.Resolvers,
directives: cfg.Directives,
complexity: cfg.Complexity,
}
}
type Config struct {
Schema *ast.Schema
Resolvers ResolverRoot
Directives DirectiveRoot
Complexity ComplexityRoot
}
type ResolverRoot interface {
Mutation() MutationResolver
Query() QueryResolver
}
type DirectiveRoot struct {
}
type ComplexityRoot struct {
Mutation struct {
Login func(childComplexity int, username string, email string) int
Logout func(childComplexity int) int
}
Query struct {
HeartBeat func(childComplexity int) int
}
}
type executableSchema struct {
schema *ast.Schema
resolvers ResolverRoot
directives DirectiveRoot
complexity ComplexityRoot
}
func (e *executableSchema) Schema() *ast.Schema {
if e.schema != nil {
return e.schema
}
return parsedSchema
}
func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) {
ec := executionContext{nil, e, 0, 0, nil}
_ = ec
switch typeName + "." + field {
case "Mutation.login":
if e.complexity.Mutation.Login == nil {
break
}
args, err := ec.field_Mutation_login_args(context.TODO(), rawArgs)
if err != nil {
return 0, false
}
return e.complexity.Mutation.Login(childComplexity, args["username"].(string), args["email"].(string)), true
case "Mutation.logout":
if e.complexity.Mutation.Logout == nil {
break
}
return e.complexity.Mutation.Logout(childComplexity), true
case "Query.heartBeat":
if e.complexity.Query.HeartBeat == nil {
break
}
return e.complexity.Query.HeartBeat(childComplexity), true
}
return 0, false
}
func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler {
rc := graphql.GetOperationContext(ctx)
ec := executionContext{rc, e, 0, 0, make(chan graphql.DeferredResult)}
inputUnmarshalMap := graphql.BuildUnmarshalerMap()
first := true
switch rc.Operation.Operation {
case ast.Query:
return func(ctx context.Context) *graphql.Response {
var response graphql.Response
var data graphql.Marshaler
if first {
first = false
ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap)
data = ec._Query(ctx, rc.Operation.SelectionSet)
} else {
if atomic.LoadInt32(&ec.pendingDeferred) > 0 {
result := <-ec.deferredResults
atomic.AddInt32(&ec.pendingDeferred, -1)
data = result.Result
response.Path = result.Path
response.Label = result.Label
response.Errors = result.Errors
} else {
return nil
}
}
var buf bytes.Buffer
data.MarshalGQL(&buf)
response.Data = buf.Bytes()
if atomic.LoadInt32(&ec.deferred) > 0 {
hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0
response.HasNext = &hasNext
}
return &response
}
case ast.Mutation:
return func(ctx context.Context) *graphql.Response {
if !first {
return nil
}
first = false
ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap)
data := ec._Mutation(ctx, rc.Operation.SelectionSet)
var buf bytes.Buffer
data.MarshalGQL(&buf)
return &graphql.Response{
Data: buf.Bytes(),
}
}
default:
return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation"))
}
}
type executionContext struct {
*graphql.OperationContext
*executableSchema
deferred int32
pendingDeferred int32
deferredResults chan graphql.DeferredResult
}
func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) {
atomic.AddInt32(&ec.pendingDeferred, 1)
go func() {
ctx := graphql.WithFreshResponseContext(dg.Context)
dg.FieldSet.Dispatch(ctx)
ds := graphql.DeferredResult{
Path: dg.Path,
Label: dg.Label,
Result: dg.FieldSet,
Errors: graphql.GetErrors(ctx),
}
// null fields should bubble up
if dg.FieldSet.Invalids > 0 {
ds.Result = graphql.Null
}
ec.deferredResults <- ds
}()
}
func (ec *executionContext) introspectSchema() (*introspection.Schema, error) {
if ec.DisableIntrospection {
return nil, errors.New("introspection disabled")
}
return introspection.WrapSchema(ec.Schema()), nil
}
func (ec *executionContext) introspectType(name string) (*introspection.Type, error) {
if ec.DisableIntrospection {
return nil, errors.New("introspection disabled")
}
return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil
}
var sources = []*ast.Source{
{Name: "../auth.graphql", Input: `extend type Mutation {
login(username: String!, email: String!): Boolean!
logout: Boolean!
}
`, BuiltIn: false},
{Name: "../index.graphql", Input: `# GraphQL schema example
#
# https://gqlgen.com/getting-started/
type Mutation
type Query {
heartBeat: Boolean!
}
"""
Maps a Time GraphQL scalar to a Go time.Time struct.
"""
scalar Time
"""
type Map(Go type: map[string]interface{})
"""
scalar Map
"""
Go type interface{}
"""
scalar Any
scalar Void
"""
directive to map Go type
type User @goModel(model: "github.com/my/app/models.User") {
id: ID! @goField(name: "todoId")
name: String!
@goField(forceResolver: true)
@goTag(key: "xorm", value: "-")
@goTag(key: "yaml")
}
"""
directive @goModel(
model: String
models: [String!]
forceGenerate: Boolean
) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION
"""
directive to map Go type
"""
directive @goField(
forceResolver: Boolean
name: String
omittable: Boolean
) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION
directive @goTag(key: String!, value: String) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION
`, BuiltIn: false},
}
var parsedSchema = gqlparser.MustLoadSchema(sources...)

52
graph/index.graphql Normal file
View File

@ -0,0 +1,52 @@
# GraphQL schema example
#
# https://gqlgen.com/getting-started/
type Mutation
type Query {
heartBeat: Boolean!
}
"""
Maps a Time GraphQL scalar to a Go time.Time struct.
"""
scalar Time
"""
type Map(Go type: map[string]interface{})
"""
scalar Map
"""
Go type interface{}
"""
scalar Any
scalar Void
"""
directive to map Go type
type User @goModel(model: "github.com/my/app/models.User") {
id: ID! @goField(name: "todoId")
name: String!
@goField(forceResolver: true)
@goTag(key: "xorm", value: "-")
@goTag(key: "yaml")
}
"""
directive @goModel(
model: String
models: [String!]
forceGenerate: Boolean
) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION
"""
directive to map Go type
"""
directive @goField(
forceResolver: Boolean
name: String
omittable: Boolean
) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION
directive @goTag(key: String!, value: String) on INPUT_FIELD_DEFINITION | FIELD_DEFINITION

28
graph/index.resolvers.go Normal file
View File

@ -0,0 +1,28 @@
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.55
import (
"context"
graph "gitserver.in/patialtech/rano/graph/generated"
)
// HeartBeat is the resolver for the heartBeat field.
func (r *queryResolver) HeartBeat(ctx context.Context) (bool, error) {
// do needful checkup
//
return true, nil
}
// Mutation returns graph.MutationResolver implementation.
func (r *Resolver) Mutation() graph.MutationResolver { return &mutationResolver{r} }
// Query returns graph.QueryResolver implementation.
func (r *Resolver) Query() graph.QueryResolver { return &queryResolver{r} }
type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }

1
graph/model/model.go Normal file
View File

@ -0,0 +1 @@
package model

View File

@ -0,0 +1,9 @@
// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.
package model
type Mutation struct {
}
type Query struct {
}

152
graph/resolver.go Normal file
View File

@ -0,0 +1,152 @@
//go:generate go run github.com/99designs/gqlgen generate
package graph
import (
"context"
"log/slog"
"net/http"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/vektah/gqlparser/gqlerror"
"gitserver.in/patialtech/rano/graph/generated"
"gitserver.in/patialtech/rano/pkg/logger"
)
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.
type Resolver struct{}
var srv *handler.Server
func init() {
srv = handler.NewDefaultServer(schema())
// limit query complexity
srv.Use(extension.FixedComplexityLimit(90))
// recover
srv.SetRecoverFunc(func(ctx context.Context, err interface{}) error {
oc := graphql.GetOperationContext(ctx)
// TODO: sanitize oc.RawQuery
logger.Error(err.(error), slog.String("gqlQuery", oc.RawQuery))
return gqlerror.Errorf("Internal server error!")
})
}
// schema creates a graphql executable schema.
func schema() graphql.ExecutableSchema {
c := generated.Config{
Resolvers: &Resolver{},
}
// c.Directives.Authorize = func(ctx context.Context, obj interface{}, next graphql.Resolver, groups []*permission.Group) (res interface{}, err error) {
// // get session user
// user := account.CtxUser(ctx)
// if user == nil {
// // session user isn't found
// return nil, errors.New("401 Unauthorized")
// }
// // has roles count more than 0
// if len(groups) == 0 { // we just want to authorize, no need to check has a role
// return next(ctx)
// }
// // user is in desired role
// for _, g := range groups {
// if g == nil {
// continue
// }
// // Role Check
// switch *g {
// case permission.GroupRFXAdmin,
// permission.GroupDealerAdmin,
// permission.GroupInstallerAdmin,
// permission.GroupIntegratorAdmin:
// if enum.RoleAdmin != user.Role {
// continue
// }
// case permission.GroupRFXUser,
// permission.GroupDealerUser,
// permission.GroupInstallerUser,
// permission.GroupIntegratorUser:
// if enum.RoleSiteUser != user.Role {
// continue
// }
// default:
// continue
// }
// // ORG must be present
// if user.Partner == nil {
// continue
// }
// // ORG Type Check
// switch *g {
// case permission.GroupRFXAdmin, permission.GroupRFXUser:
// if enum.PartnerRFX == user.Partner.Type {
// return next(ctx)
// }
// case permission.GroupDealerAdmin, permission.GroupDealerUser:
// if enum.PartnerDealer == user.Partner.Type {
// return next(ctx)
// }
// case permission.GroupInstallerAdmin, permission.GroupInstallerUser:
// if enum.PartnerInstaller == user.Partner.Type {
// return next(ctx)
// }
// case permission.GroupIntegratorAdmin, permission.GroupIntegratorUser:
// if enum.PartnerIntegrator == user.Partner.Type {
// return next(ctx)
// }
// }
// }
// // failed, user is not authorized to go next
// return nil, msg.NewError(msg.NotAuthorized)
// }
// c.Directives.FieldFor = func(
// ctx context.Context, obj interface{}, next graphql.Resolver, roles []*enum.Role, defaultVal interface{},
// ) (res interface{}, err error) {
// // get session user
// user := account.CtxUser(ctx)
// if user == nil { // return empty if user info not found
// return "", nil
// }
// // check user has a role allowed for current operation
// for _, role := range roles {
// if role != nil && user.Role == *role {
// // on match just call next
// return next(ctx)
// }
// }
// return defaultVal, nil
// }
return generated.NewExecutableSchema(c)
}
// GraphiQL route handler
func GraphiQL(queryEndpoint string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
h := playground.Handler("GraphQL", queryEndpoint)
h.ServeHTTP(w, r)
}
}
// Query graph
func Query(w http.ResponseWriter, r *http.Request) {
// srv.ServeHTTP(w, r.WithContext(userCtx(r)))
srv.ServeHTTP(w, r)
}

34
graph/server/main.go Normal file
View File

@ -0,0 +1,34 @@
package main
import (
"net/http"
"os"
"gitserver.in/patialtech/mux"
"gitserver.in/patialtech/rano/graph"
"gitserver.in/patialtech/rano/pkg/logger"
)
func main() {
r := mux.NewRouter()
// graphiql
r.Get("/graphiql", graph.GraphiQL("/query"))
// graph query
r.Post("/query", graph.Query)
// catch all
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello there"))
})
port := os.Getenv("GRAPH_PORT")
if port == "" {
port = "4001"
}
r.Serve(func(srv *http.Server) error {
srv.Addr = ":" + port
logger.Info("graph server listening on %s", srv.Addr)
return srv.ListenAndServe()
})
}

2
graphql.config.yml Normal file
View File

@ -0,0 +1,2 @@
schema: 'graph/*.graphql' # or 'http://localhost:9876/graphql'
documents: 'graph/**/*'

23
houdini.config.js Normal file
View File

@ -0,0 +1,23 @@
/// <references types="houdini-svelte">
/** @type {import('houdini').ConfigFile} */
const config = {
watchSchema: {
url: process.env.GRAPH_HOST,
headers: {
Authentication() {
const token = localStorage.getItem('AUTH_TOKEN') ?? '';
return `Bearer ${token}`;
}
}
},
plugins: {
'houdini-svelte': {
projectDir: './web',
client: './web/lib/gqlClient',
include: './web/**/*.{svelte,graphql,gql,ts,js}'
}
}
};
export default config;

View File

@ -8,20 +8,36 @@
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/adapter-static": "^3.0.5", "@sveltejs/adapter-static": "^3.0.5",
"@sveltejs/kit": "^2.7.2", "@sveltejs/kit": "^2.7.2",
"@sveltejs/vite-plugin-svelte": "^4.0.0-next.8", "@sveltejs/vite-plugin-svelte": "^4.0.0-next.8",
"@tailwindcss/aspect-ratio": "^0.4.2", "@tailwindcss/aspect-ratio": "^0.4.2",
"@tailwindcss/container-queries": "^0.1.1",
"@tailwindcss/forms": "^0.5.9",
"@tailwindcss/typography": "^0.5.15", "@tailwindcss/typography": "^0.5.15",
"@types/eslint": "^9.6.0",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"daisyui": "^4.12.13", "daisyui": "^4.12.13",
"postcss": "^8.4.47", "eslint": "^9.7.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"globals": "^15.0.0",
"graphql": "^16.9.0",
"houdini": "^1.3.0",
"houdini-svelte": "^2.0.0",
"prettier": "^3.3.2",
"prettier-plugin-svelte": "^3.2.6",
"prettier-plugin-tailwindcss": "^0.6.5",
"svelte": "^5.0.5", "svelte": "^5.0.5",
"svelte-check": "^4.0.5", "svelte-check": "^4.0.5",
"tailwindcss": "^3.4.14", "tailwindcss": "^3.4.14",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0",
"vite": "^5.0.3" "vite": "^5.0.3"
} }
} }

31
pkg/logger/logger.go Normal file
View File

@ -0,0 +1,31 @@
package logger
import (
"fmt"
"log/slog"
)
func Info(msg string, args ...any) {
a, b := getArgs(args)
slog.Info(fmt.Sprintf(msg, a...), b...)
}
func Error(err error, args ...any) {
a, b := getArgs(args)
slog.Error(fmt.Sprintf(err.Error(), a...), b...)
// TODO: save error log for later scrutiny
}
func getArgs(args []any) ([]any, []any) {
var a []any
var b []any
for _, arg := range args {
switch arg.(type) {
case slog.Attr:
b = append(b, arg)
default:
a = append(a, arg)
}
}
return a, b
}

58
schema.graphql Normal file
View File

@ -0,0 +1,58 @@
"""
The @defer directive may be specified on a fragment spread to imply de-prioritization, that causes the fragment to be omitted in the initial response, and delivered as a subsequent response afterward. A query with @defer directive will cause the request to potentially return multiple responses, where non-deferred data is delivered in the initial response and data deferred delivered in a subsequent response. @include and @skip take precedence over @defer.
"""
directive @defer(if: Boolean = true, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT
"""
directive to map Go type
"""
directive @goField(
forceResolver: Boolean
name: String
omittable: Boolean
) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
"""
directive to map Go type
example:-
type User @goModel(model: "github.com/my/app/models.User") {
id: ID! @goField(name: "todoId")
name: String!
@goField(forceResolver: true)
@goTag(key: "xorm", value: "-")
@goTag(key: "yaml")
}
"""
directive @goModel(
forceGenerate: Boolean
model: String
models: [String!]
) on ENUM | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION
directive @goTag(key: String!, value: String) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
"""
Go type interface{}
"""
scalar Any
"""
type Map(Go type: map[string]interface{})
"""
scalar Map
type Mutation {
login(email: String!, username: String!): Boolean!
logout: Boolean!
}
type Query {
heartBeat: Boolean!
}
"""
Maps a Time GraphQL scalar to a Go time.Time struct.
"""
scalar Time
scalar Void

View File

@ -1,16 +0,0 @@
package main
import (
"net/http"
"gitserver.in/patialtech/mux"
)
func router() *mux.Router {
r := mux.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello there"))
})
return r
}

View File

@ -1,5 +0,0 @@
package main
func main() {
}

View File

@ -1,37 +1,40 @@
import adapter from "@sveltejs/adapter-static"; import path from 'node:path';
import adapter from '@sveltejs/adapter-static';
const webDir = path.resolve('.', 'web');
const webDir = "./web";
/** @type {import('@sveltejs/kit').Config} */ /** @type {import('@sveltejs/kit').Config} */
const config = { const config = {
kit: { kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter. // If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters. // See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter(), adapter: adapter(),
files: { files: {
appTemplate: `${webDir}/app.html`, appTemplate: path.resolve(webDir, 'app.html'),
routes: `${webDir}/routes`, routes: path.resolve(webDir, 'routes'),
lib: `${webDir}/lib`, lib: path.resolve(webDir, 'lib'),
assets: `${webDir}/public`, assets: path.resolve(webDir, 'public')
}, },
alias: { alias: {
"$image/*": `${webDir}/assets/image/*`, $image: path.resolve(webDir, 'assets', 'image'),
"$svg/*": `${webDir}/assets/svg/*`, $svg: path.resolve(webDir, 'assets', 'svg'),
}, $houdini: path.resolve('.', '$houdini')
paths: { },
assets: process.env.ASSETS_HOST ?? "", paths: {
}, assets: process.env.ASSETS_HOST ?? ''
version: { },
name: `v-${Date.now()}`, version: {
pollInterval: 1000 * 60 * 1, // 5 minutes name: `v-${Date.now()}`,
}, pollInterval: 1000 * 60 * 1 // 5 minutes
adapter: adapter({ },
pages: `${webDir}/public/build`, adapter: adapter({
assets: `${webDir}/public/build`, pages: path.resolve(webDir, 'public', 'build'),
fallback: "fallback.html", assets: path.resolve(webDir, 'public', 'build'),
strict: true, fallback: 'fallback.html',
}), strict: true
}, })
}
}; };
export default config; export default config;

View File

@ -1,12 +0,0 @@
import typography from "@tailwindcss/typography";
import aspect from "@tailwindcss/aspect-ratio";
import daisy from "daisyui";
/** @type {import('tailwindcss').Config} */
export default {
content: ["./web/routes/**/*.{svelte,js}"],
plugins: [typography, aspect, daisy],
theme: {
extend: {},
},
};

14
tailwind.config.ts Normal file
View File

@ -0,0 +1,14 @@
import aspectRatio from '@tailwindcss/aspect-ratio';
import containerQueries from '@tailwindcss/container-queries';
import forms from '@tailwindcss/forms';
import typography from '@tailwindcss/typography';
import type { Config } from 'tailwindcss';
import daisy from "daisyui";
export default {
content: ["./web/routes/**/*.{svelte,js}"],
plugins: [typography, forms, containerQueries, aspectRatio, daisy],
theme: {
extend: {},
},
} satisfies Config;

35
taskfile.yml Normal file
View File

@ -0,0 +1,35 @@
version: '3'
env:
ENV: development
tasks:
gen:
desc: use go generate, for graph files
preconditions:
- go mod tidy
cmds:
- go generate ./graph
check:
desc: perform go vuln check
cmds:
- govulncheck -show verbose ./...
install:
desc: install packages
cmds:
- deno install --allow-scripts=npm:@sveltejs/kit
graph:
desc: run graph server
cmds:
- cmd: go run ./graph/server
env:
GRAPH_PORT: 3009
web:
desc: run web in dev mode
cmds:
- cmd: deno task dev
env:
WEB_PORT: 3006
GRAPH_HOST: http://localhost:3009/query

8
tools.go Normal file
View File

@ -0,0 +1,8 @@
//go:build tools
package tools
import (
_ "github.com/99designs/gqlgen"
_ "github.com/99designs/gqlgen/graphql/introspection"
)

View File

@ -9,10 +9,11 @@
"skipLibCheck": true, "skipLibCheck": true,
"sourceMap": true, "sourceMap": true,
"strict": true, "strict": true,
"moduleResolution": "bundler" "moduleResolution": "bundler",
"rootDirs": ["./web", "./.svelte-kit/types", "./$houdini/types"]
} }
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
// //
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in // from the referenced tsconfig.json - TypeScript does not merge them in

View File

@ -1,11 +1,13 @@
import { sveltekit } from "@sveltejs/kit/vite"; import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from "vite"; import houdini from 'houdini/vite';
import { defineConfig } from 'vite';
export default defineConfig({ export default defineConfig({
plugins: [sveltekit()], plugins: [houdini(), sveltekit()],
server: { server: {
fs: { port: parseInt(process.env.WEB_PORT ?? '3001'),
allow: ["./web/app.css", "./web/assets"], fs: {
}, allow: ['./web/app.css', './web/assets']
}, }
}
}); });

5
web/lib/gqlClient.ts Normal file
View File

@ -0,0 +1,5 @@
import { HoudiniClient } from '$houdini';
export default new HoudiniClient({
url: process.env.GRAPH_HOST
});

12
web/lib/ui/Btn.svelte Normal file
View File

@ -0,0 +1,12 @@
<script lang="ts">
import { type Snippet } from "svelte";
interface Props {
children: Snippet
}
const { children }:Props = $props();
</script>
<button>
{@render children()}
</button>