Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Last active April 25, 2025 03:32
Show Gist options
  • Save alexesDev/5c1b3f544c545316c07fee5872443f0a to your computer and use it in GitHub Desktop.
Save alexesDev/5c1b3f544c545316c07fee5872443f0a to your computer and use it in GitHub Desktop.
https://mol.hyoo.ru + GraphQL v2
export class $yourproject_auth_email_form extends $.$yourproject_auth_email_form {
@$mol_mem
request_error(next?: string): string {
return next ?? ''
}
submit() {
const res = $yourproject_graphql_request(
/* GraphQL */ `
mutation RequestEmailSignInCode($input: RequestEmailSignInCodeInput!) {
data: requestEmailSignInCode(input: $input) {
... on ErrorPayload {
__typename
message
}
... on RequestEmailSignInCodePayload {
__typename
success
}
}
}
`,
{
input: {
email: this.email(),
},
}
)
if (res.data.__typename === 'ErrorPayload') {
this.request_error(res.data.message)
return
}
if (res.data.__typename === 'RequestEmailSignInCodePayload') {
if (res.data.success) {
this.$.$mol_state_arg.value('email', this.email())
return
}
}
this.request_error('Unknown error')
}
}

Создать примерно такую структуру

yourproject/
  -graphqlgen.js # Конфиг кодгена, mam пропускает все файлы с ^-
  -graphqlmol.js # Плагин под $mol_data
  graphql
    request.ts # Файл ниже, базовая функция запроса
    queries.ts # Будет создан код геном
    

После вызовы кодгена

npx graphql-codegen --config myproject/-graphqlgen.js

request.ts нужно будет реализовать под свой проект, с токенами в заголовкой и тп

typescript plugin генерирует $fragmentName в типах и mam пытается подклоючить такой пакет, его понятно нет. Так же в запросах скорее всего будет $input переменная, которая так же будет воспринята mam как пакет. Чтобы это обойти можно просто сделать в корне mam:

mkdir fragment
mkdir input
module.exports = {
schema: 'http://localhost:8081/graphql',
documents: [__dirname + '/**/*.ts'],
generates: {
[__dirname + '/graphql/queries.ts']: {
plugins: [
{
add: {
content: 'namespace $.$$ {\n\n',
},
},
'typescript',
'typescript-operations',
__dirname + '/-graphqlmol.js',
],
config: {
noExport: true,
molPrefix: '$yourproject_graphql', // FIX ME!
},
},
},
}
const { print, stripIgnoredCharacters } = require('graphql')
const { pascalCase } = require('change-case')
module.exports.plugin = (schema, documents, config) => {
const operations = []
const lines = []
const molPrefix = config.molPrefix || 'change_in_the_config'
for (const doc of documents) {
if (!doc.document) {
continue
}
for (const def of doc.document.definitions) {
if (def.kind !== 'OperationDefinition' || !def.name) continue
let prefix = 'Query'
if (def.operation === 'mutation') {
prefix = 'Mutation'
}
operations.push({
source: doc.rawSDL,
variablesType: `${def.name.value}${prefix}Variables`,
resultType: `${def.name.value}${prefix}`,
hasVars: (def.variableDefinitions?.length || 0) > 0,
})
}
}
for (const op of operations) {
const lit = op.source.replace(/\n/g, '\\n').replace(/\t/g, '\\t')
let vars = ''
let passVars = ''
if (op.hasVars) {
vars = `, variables: ${op.variablesType}`
passVars = `, variables`
}
lines.push(`export function ${molPrefix}_request(query: '${lit}'${vars}): ${op.resultType}`)
}
lines.push(
`export function ${molPrefix}_request(query: any, variables?: any) { return ${molPrefix}_raw_request(query, variables); }`
)
return lines.join('\n\n') + '\n\n}'
}
namespace $ {
export class $yourproject_graphql_error extends Error {
constructor(message: string, public detail?: unknown) {
super(message)
}
}
export function $yourproject_graphql_raw_request(query: string, variables?: any) {
const res = $.$mol_fetch.json('/graphql', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
}) as { data?: any; errors?: any[] }
if (res.errors) {
throw new $yourproject_graphql_error('GraphQL Error', res.errors)
}
return res.data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment