Giter VIP home page Giter VIP logo

graphcool-templates's Introduction

Graphcool Templates πŸ“—

Use Graphcool templates to quickly pull in predefined functionality into your own Graphcool service.

Overview

Officially supported templates

We maintain a number of officially supported templates:

Outdated templates

Notice that the outdated templates are not officially supported. Right now, most of the templates inside the outdated directory are not working when used with the graphcool-framework add-template command!

Contributions

Contributions are highly welcome πŸ’š if you'd like to add a new template, you can get inspiration from the help wanted label, or suggest your own template!

Adding templates to your service

There are two ways how you can use a template in your service:

  1. Manually download and copy the code from a template directory in this repository.
  2. Use the add-template command from the CLI.

Option 1: Manually adding templates

The process of adding a template to a Graphcool service involves several steps. You're basically merging your local service definition with the service definition of the template you want to use. In the end, you end up with only one graphcool.yml as well as only one types.graphql.

Adding a template manually:

  1. Download the folder that contains the service definition of the template you want to use.
  2. Copy that folder into the root directory of your Graphcool service.
  3. Copy over the contents from the template's graphcool.yml into the graphcool.yml of your own service. Be sure to adjust any file references, e.g. source files that contain code for functions, if necessary.
  4. Copy over the contents from the template's types.graphql into the types.graphql of your own service.
  5. Deploy your changes with graphcool deploy.

Option 2: Adding templates with the CLI

The add-template command in the Graphcool CLI basically automates the process of manually adding templates.

Official templates can be added by providing their relative path in this repository, e.g. for the email-password-template:

graphcool-framework add-template auth/email-password

To install your own templates, you can provide the path to a GitHub repository, too:

graphcool-framework add-template graphcool/templates/auth/email-password

When merging the template's graphcool.yml and types.graphql files with the ones from your local service definition, the CLI will only add the contents from the template files into your local files as comments. So you need to explicitly uncomment the parts form the template files that you actually want to use in your service.

The process for using the CLI to add a template thus looks as follows:

  1. Use the add-template <path> CLI command and specify the <path> which points to the template's directory in this repository.
  2. Uncomment the lines in graphcool.yml and types.graphql.
  3. Deploy your changes with graphcool deploy.

Contributors

A big thank you to all contributors and supporters of this repository πŸ’š

marktani yusinto kuldar heymartinadams pbassut kbrandwijk dkh215 sorenbs petrvlcek mwickett katopz randomer picosam antho1404 BoraKilicoglu peterpme Gregor1971 jhalborg felipesabino iamclaytonray fdidron

Help & Community Slack Status

Say hello in our Slack or visit the Graphcool Forum if you run into issues or have questions. We love talking to you!

graphcool-templates's People

Contributors

abeagley avatar antho1404 avatar aurnik avatar borakilicoglu avatar denkristoffer avatar fabien0102 avatar fdidron avatar felipesabino avatar heymartinadams avatar katopz avatar kbrandwijk avatar kuldar avatar marktani avatar millergregor avatar mrwillis avatar mwickett avatar nikolasburk avatar pbassut avatar peterpme avatar petrvlcek avatar picosam avatar ragzor avatar randomer avatar ronthedrummer avatar schickling avatar sorenbs avatar stevewpatterson avatar timsuchanek avatar wdoug avatar yusinto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphcool-templates's Issues

Templates should be written in TypeScript

Issue type:

I am submitting:

  • an issue
  • a feature request

What feature would you like to see added? Please be descriptive.

I would like to see all examples to be written in TypeScript to encourage people to adopt it. It makes a lot of sense to write resolvers in TS since it would help make them more robust and less bug prone.

Would you be able to submit a PR for this yourself?

Yes, I might be able to contribute to some of them.

Email-password authentication returning an unhandled error

Hi,
I followed the instructions here to install the email-password template.

Running the example mutation

mutation {
  signupUser(email: "[email protected]", password: "__PASSWORD__") {
    token
  }
}

The following error arises

{
  "data": {
    "signupUser": null
  },
  "errors": [
    {
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "signupUser"
      ],
      "code": 5000,
      "message": "A function returned an unhandled error. Please check the logs for executionId 'eu-west-1:simple:cj9tyz5jl08nt0175m45favux'",
      "requestId": "eu-west-1:simple:cj9tyz5jl08nt0175m45favux"
    }
  ]
}

Create language branches so people can easily contribute in their own programming language

Issue type:

I am submitting:

  • an issue
  • a feature request

What feature would you like to see added? Please be descriptive.

I would like multiple language branches (at least Javascript and Typescript), so people can easily use and contribute to templates in their preferred programming language.

The CLI already supports branches by doing:
graphcool add-template github/templates#typescript/auth/email-password

Would you be able to submit a PR for this yourself?

Yes

email-user-management An unexpected error occured

Hello!
Help me please. I want to update user password. I copied the schema code and logic according to the instructions. Next I created a pta on the AUTHENTICATION tab.
I call a mutation:

mutation {
 updatePassword(email: "user_email", password: "pass", newPassword: "new_pass") {
    id
 }
}

But I get an error: 'GraphQL error: function execution error: An unexpected error occured.'.

If I do the 'test run':

{
    "data": {
        "email": "user_email",
        "password": "pass",
        "newPassword": "new_pass",
    },
    "context": {
        "projectId": "projectId",
        "pat": "pat",
  },
}

I get an error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://console.graph.cool' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
fullscreen:1 Uncaught (in promise) TypeError: Failed to fetch

Tell me please, what could be the problem?

Simpler onboarding

doing graphcool add-template email-password

would be much easier and intuitive
instead of
graphcool add-template graphcool/templates/auth/email-password

Relations management example

It would be nice to see some example of calling a mutation in response to a node creation which should create defaults relations, for example, adding a newly created user to a given group, and make sure the response payload could return the freshly created relation

Email / Password template : Passwords revealed in function error logs

Issue type:

I am submitting:

  • an issue
  • a feature request

Issue Questions:

What OS and OS version are you experiencing the issue(s) on?

Applies to any OS / OS Version

What is the expected behavior?

The data passed to functions should be logged conditionally by setting an environment var for example (DEBUG = true)

What is the actual behavior?

When checking the execution logs of the signup function, the password is displayed in plain text if the execution resulted in an error. This also affects the authenticate function.

What steps may we take to reproduce the behavior?

  1. Setup a project with email/password auth template
  2. Trigger a Email already in use error by trying to signup with an existing email address
  3. Check the signup function execution logs: gc logs -f signup

503 error when using exact signup schema extension in email auth example

I am getting an extremely cryptic error when using the signup schema extension in the email auth example. I've copied the code verbatim and created a PAT with the same name 'signupEmailUser', but I receive this odd error when running a simple query in the playground as suggested. Here is my extension which is copy pasted from here

type SignupEmailUserPayload {
  id: ID!
}

extend type Mutation {
  signupEmailUser(email: String!, password: String!): SignupEmailUserPayload
}

and my code which is straight copy pasted from the example here:

const fromEvent = require('graphcool-lib').fromEvent
const bcrypt = require('bcrypt')
const validator = require('validator')
const crypto = require('crypto')

module.exports = function(event) {
  const email = event.data.email
  const password = event.data.password
  const graphcool = fromEvent(event)
  const api = graphcool.api('simple/v1')
  const SALT_ROUNDS = 10

  function getGraphcoolUser(email) {
    return api.request(`
    query {
      User(email: "${email}") {
        id
      }
    }`)
      .then((userQueryResult) => {
        if (userQueryResult.error) {
          return Promise.reject(userQueryResult.error)
        } else {
          return userQueryResult.User
        }
      })
  }

  function generateToken() {
    return crypto.randomBytes(20).toString("hex")
  }

  function generateExpiration() {
    const now = new Date()
    return new Date(now.getTime() + 3600000).toISOString()
  }

  function createGraphcoolUser(email, passwordHash) {
    return api.request(`
      mutation {
        createUser(
          email: "${email}",
          password: "${passwordHash}",
          confirmToken: "${generateToken()}",
          confirmExpires: "${generateExpiration()}"
        ) {
          id
        }
      }`)
      .then((userMutationResult) => {
        return userMutationResult.createUser.id
      })
  }

  if (validator.isEmail(email)) {
    return getGraphcoolUser(email)
      .then((graphcoolUser) => {
        if (graphcoolUser === null) {
          return bcrypt.hash(password, SALT_ROUNDS)
            .then(hash => createGraphcoolUser(email, hash))
        } else {
          return Promise.reject("Email already in use")
        }
      })
      .then((id) => {
        return { data: { id } }
      })
      .catch((error) => {
        console.log(error)

        // don't expose error message to client!
        return { error: 'An unexpected error occured.' }
      })
  } else {
    return { error: "Not a valid email" }
  }
}

Clearly I am getting the line right under // don't expose error message to client! but I have no idea what the console.log is above!!!

My mutation is the following as suggested:

mutation {
  # replace __EMAIL__ and __PASSWORD__
  signupEmailUser(email: "[email protected]", password: "password") {
    id
  }
}

And my error:

{"event":"{\"data\":{\"email\":\"[email protected]\",\"password\":\"password\"},\"context\":{\"request\":{\"sourceIp\":\"[REMOVED]\",\"headers\":{},\"httpMethod\":\"post\"},\"auth\":null,\"sessionCache\":{},\"environment\":{},\"graphcool\":{\"projectId\":\"[REMOVED]\",\"alias\":\"[REMOVED]\",\"pat\":\"[REMOVED]"}}}","logs":["2017-09-29T00:11:23.397Z: {\"response\":{\"0\":\"<\",\"1\":\"h\",\"2\":\"t\",\"3\":\"m\",\"4\":\"l\",\"5\":\">\",\"6\":\"\\r\",\"7\":\"\\n\",\"8\":\"<\",\"9\":\"h\",\"10\":\"e\",\"11\":\"a\",\"12\":\"d\",\"13\":\">\",\"14\":\"<\",\"15\":\"t\",\"16\":\"i\",\"17\":\"t\",\"18\":\"l\",\"19\":\"e\",\"20\":\">\",\"21\":\"5\",\"22\":\"0\",\"23\":\"3\",\"24\":\" \",\"25\":\"S\",\"26\":\"e\",\"27\":\"r\",\"28\":\"v\",\"29\":\"i\",\"30\":\"c\",\"31\":\"e\",\"32\":\" \",\"33\":\"T\",\"34\":\"e\",\"35\":\"m\",\"36\":\"p\",\"37\":\"o\",\"38\":\"r\",\"39\":\"a\",\"40\":\"r\",\"41\":\"i\",\"42\":\"l\",\"43\":\"y\",\"44\":\" \",\"45\":\"U\",\"46\":\"n\",\"47\":\"a\",\"48\":\"v\",\"49\":\"a\",\"50\":\"i\",\"51\":\"l\",\"52\":\"a\",\"53\":\"b\",\"54\":\"l\",\"55\":\"e\",\"56\":\"<\",\"57\":\"/\",\"58\":\"t\",\"59\":\"i\",\"60\":\"t\",\"61\":\"l\",\"62\":\"e\",\"63\":\">\",\"64\":\"<\",\"65\":\"/\",\"66\":\"h\",\"67\":\"e\",\"68\":\"a\",\"69\":\"d\",\"70\":\">\",\"71\":\"\\r\",\"72\":\"\\n\",\"73\":\"<\",\"74\":\"b\",\"75\":\"o\",\"76\":\"d\",\"77\":\"y\",\"78\":\" \",\"79\":\"b\",\"80\":\"g\",\"81\":\"c\",\"82\":\"o\",\"83\":\"l\",\"84\":\"o\",\"85\":\"r\",\"86\":\"=\",\"87\":\"\\\"\",\"88\":\"w\",\"89\":\"h\",\"90\":\"i\",\"91\":\"t\",\"92\":\"e\",\"93\":\"\\\"\",\"94\":\">\",\"95\":\"\\r\",\"96\":\"\\n\",\"97\":\"<\",\"98\":\"c\",\"99\":\"e\",\"100\":\"n\",\"101\":\"t\",\"102\":\"e\",\"103\":\"r\",\"104\":\">\",\"105\":\"<\",\"106\":\"h\",\"107\":\"1\",\"108\":\">\",\"109\":\"5\",\"110\":\"0\",\"111\":\"3\",\"112\":\" \",\"113\":\"S\",\"114\":\"e\",\"115\":\"r\",\"116\":\"v\",\"117\":\"i\",\"118\":\"c\",\"119\":\"e\",\"120\":\" \",\"121\":\"T\",\"122\":\"e\",\"123\":\"m\",\"124\":\"p\",\"125\":\"o\",\"126\":\"r\",\"127\":\"a\",\"128\":\"r\",\"129\":\"i\",\"130\":\"l\",\"131\":\"y\",\"132\":\" \",\"133\":\"U\",\"134\":\"n\",\"135\":\"a\",\"136\":\"v\",\"137\":\"a\",\"138\":\"i\",\"139\":\"l\",\"140\":\"a\",\"141\":\"b\",\"142\":\"l\",\"143\":\"e\",\"144\":\"<\",\"145\":\"/\",\"146\":\"h\",\"147\":\"1\",\"148\":\">\",\"149\":\"<\",\"150\":\"/\",\"151\":\"c\",\"152\":\"e\",\"153\":\"n\",\"154\":\"t\",\"155\":\"e\",\"156\":\"r\",\"157\":\">\",\"158\":\"\\r\",\"159\":\"\\n\",\"160\":\"<\",\"161\":\"/\",\"162\":\"b\",\"163\":\"o\",\"164\":\"d\",\"165\":\"y\",\"166\":\">\",\"167\":\"\\r\",\"168\":\"\\n\",\"169\":\"<\",\"170\":\"/\",\"171\":\"h\",\"172\":\"t\",\"173\":\"m\",\"174\":\"l\",\"175\":\">\",\"176\":\"\\r\",\"177\":\"\\n\",\"status\":503},\"request\":{\"query\":\"\\n    query {\\n      User(email: \\\"[email protected]\\\") {\\n        id\\n      }\\n    }\"}}"],"returnValue":{"error":"An unexpected error occured."}}

What does the above mean? :(

Auth-templates for Linkedin and Twitter

Issue type:

I am submitting:

  • an issue
  • a feature request

Feature Request Questions:

What feature would you like to see added? Please be descriptive.

Auth-teamplates for Linkedin and Twitter.

Would you be able to submit a PR for this yourself?

yes

upgrade to TS

progress see #97

see auth/email-password/src/signup.ts


  • github auth template
  • facebook, google, email-password
  • update all messaging modules to ts + README @marktani

'authProvider' is required for createUser mutation

mutation {
        createUser(
          accountKitUserId:"${accountKitUser.id}"
        ){
          id
        }
      }

this mutation is not valid in case if β€˜Email-password auth’ integration is enabled - the β€˜authProvider’ field is required.

Google auth mutation is not working

Issue type:

I am submitting:

  • an issue

Issue Questions:

What OS and OS version are you experiencing the issue(s) on?

Deployed from windows. (graphcool/0.8.5 (windows-x64) node-v7.6.)

What is the expected behavior?

Function should return token.

What is the actual behavior?

Function returning error (in logs) for googleAuthentication:

{"error":"Function returned invalid status code: 0. Raw body: empty.last"}

What steps may we take to reproduce the behavior?

Install graphcool add-template graphcool/templates/auth/google, deploy and use in GraphQL console with google token.

mutation {
	authenticateGoogleUser(googleToken:
"correct_token...") {
    token
  }  
}

I got feeling that it's some issue with using async/await, cause similar, or same issue I've got with example hello world (TypeScript) example deployed to graphcool service

emailSubscription issue at signupEmailUser function

I'm getting this issue like this, Error: Argument 'emailSubscription' expected type 'Boolean' but got: "true".

function createGraphcoolUser(email, passwordHash, name, emailSubscription) {
    return api.request(`
        mutation {
            createUser(
                email: "${email}",
                password: "${passwordHash}",
		name: "${name}",
		emailSubscription: "${emailSubscription}"
            ) {
          id
        }
        }`).then((userMutationResult) => {
            return userMutationResult.createUser.id
        }
    )
}

Everything looks right and field data type boolean.

Reject updating a node if a specific condition is true

require('isomorphic-fetch')

module.exports = function (event, cb) {
  var endpoint = 'https://api.graph.cool/simple/v1/__PROJECT_ID__'
  var token = 'Bearer __PAT__'

  var postId = event.data.id
  console.log(event.data)
  
  var query = `{
    Post(id: "${postId}") {
      isPublished
    }
  }`

  return fetch(endpoint, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify({ query })
  }).then((response) => {
    return response.json()
  }).then((data) => {
    console.log(data)
    if (data.data.Post.isPublished) {
      console.log('all good')
      return event 
    } else {
      console.log(`Unexpected update for Post ${postId}`)
      return {error: "Post not open for editing!"} 
    }
  })
}

Auth0 authentication broken on React Native

Issue type:

I am submitting:

  • [ X ] an issue

Issue Questions:

What OS and OS version are you experiencing the issue(s) on?

[email protected], [email protected], [email protected].

What is the actual behavior?

Authentication fails with app-side error: "[Error: GraphQL error: function execution error: An unexpected error occured]".

In graphcool function log we can see:

{"event":"{"data":{"accessToken":"[redacted]"},"context":{"request":{"sourceIp":"54.199.218.174","headers":{},"httpMethod":"post"},"auth":null,"sessionCache":{},"environment":{},"graphcool":{"rootToken":"[redacted]","endpoints":{"simple":"https://api.graph.cool/simple/v1/cj9q9rwxnc7z80136mm3gr6wq\",\"relay\":\"https://api.graph.cool/relay/v1/cj9q9rwxnc7z80136mm3gr6wq\",\"system\":\"https://api.graph.cool/system\",\"subscriptions\":\"wss://subscriptions.us-west-2.graph.cool/v1/cj9q9rwxnc7z80136mm3gr6wq\"},\"projectId\":\"cj9q9rwxnc7z80136mm3gr6wq\",\"alias\":null,\"pat\":\"[redacted]",\"serviceId\":\"cj9q9rwxnc7z80136mm3gr6wq\"}}}","logs":[{"2017-11-13T03:41:39.682Z":"Error: Unable to retrieve key identifier from token\n at /var/task/src/auth0/auth0Authentication.js:49:19\n at verifyToken (/var/task/src/auth0/auth0Authentication.js:45:12)\n at Object. (/var/task/src/auth0/auth0Authentication.js:104:38)\n at step (/var/task/src/auth0/auth0Authentication.js:32:23)\n at Object.next (/var/task/src/auth0/auth0Authentication.js:13:53)\n at /var/task/src/auth0/auth0Authentication.js:7:71\n at __awaiter (/var/task/src/auth0/auth0Authentication.js:3:12)\n at exports.default (/var/task/src/auth0/auth0Authentication.js:94:45)\n at executeFunction (/var/task/src/auth0/auth0Authentication-lambda.js:12:19)\n at exports.handle (/var/task/src/auth0/auth0Authentication-lambda.js:7:3)"}],"returnValue":{"error":"An unexpected error occured"}}

What steps may we take to reproduce the behavior?

Setup react-native-auth0 as per: https://github.com/auth0/react-native-auth0, using webAuth.

Follow steps in: https://github.com/graphcool/templates/tree/master/auth/auth0. Then change auth0 client type to "Native" and enable the "Authorization Code" grant type.

Then try sign-up/login using Facebook/Google/email. Error is same for each case.

Geocode, adding additional fields to payload?

Documentation says: You can only transform arguments that are part of the initial input data of the mutation on the client. You cannot add or remove additional fields.

Yet, the function will add multiple fields to a mutation that only contains two input fields. Does this actually work?

Utility functions in a template - Please vote

Currently, utility functions are not supported very well in the current templates. I'm proposing (and will implement in a PR if I receive enough upvotes), a bunch of functions for common tasks.

  • Password hashing/salting/encryption
  • Email verification (checks to see if the email is valid; if not, reformats the email)
  • Slug verification (similar as above)
  • Phone number verification (similar as above)

That's enough to get started with, for now. I'd love to hear other general utility functions that you see a use-case for.

Please only vote on this issue. Do not spam with a million comments. To make it easier, I have voted with a thumbs up and a thumbs down. Please keep comments to other features and questions so that we can be more productive.

Also, happy Thanksgiving everyone!

Consider adding tslint

As more people contribute and the repo grows larger, I could see a lot of inconsistency arising. To prevent that and to make sure we all write the same "standards" in our code, should we lint?

AuthenticateEmailUser Issue

I'm getting this issue at authenticateEmailUser.js

GraphQL error: function execution error: Error: Graphcool must be instantiated with a pat when calling 'generateAuthToken': new Graphcool('project-id', {pat: 'pat'})

Function idea: standard implementation for authy/twilio API

Just putting this out here in case anyone else is considering this. Authy/twilio offers standard flows for phone number verification, one time codes, and some other APIs (phone intelligence etc.). It would be nice to have a standard SE implementation of these APIs in this repo.

SMS Auth

Currently following the steps for sms auth

When I get to the following step it fails

Create a new Schema Extension Function called confirmUserSmsToken and paste the schema from confirm-code-schema-extension.graphql and code from sms-authentication.js.

This is the error that pops up

Function with name 'confirmUserSmsToken' has invalid payloadName: 'AuthenticateSmsUserPayload'

geocode - array position changes depending on google data set

Hi, great work on the geocode function. More of a question than issue....
I am a newb to coding and Graph.cool so hopefully you could help out.
When running that function the data in the array result may change positions...
For instance an address that has a "neighborhood" type will shift the "locality" to [3],
where as an address without a "neighborhood" type "locality" lives in the [2] position.
Using static data I reworked some things from other questions on SO....to return values by type.
My question is how would I implement the comparison function into your code?
Thanks in advance for any help on this!

function getMatchedTypes() {
  let i,
      j,
      types;
  let address_component = {}
  // Loop through the Geocoder result set. Note that the results
// array will change as this loop can self iterate.
  for (i = 0; i < address_components.length; i++) {

    address_component = address_components[i];

    types = address_component.types;

    for (j = 0; j < types.length; j++) {
      if (types[j] === 'street_number') {
        streetNumber = address_component.long_name;
      }
      if (types[j] === 'route') {
        street = address_component.long_name;
      }
      if (types[j] === 'neighborhood') {
        neighborhood = address_component.long_name;
      }
      if (types[j] === 'locality') {
        city = address_component.long_name;
      }
      if (types[j] === 'administrative_area_level_1') {
        state = address_component.long_name;
      }
      if (types[j] === 'administrative_area_level_2') {
        county = address_component.long_name;
      }
      if (types[j] === 'postal_code') {
        zip = address_component.long_name;
      }
      if (types[j] === 'postal_code_suffix') {
        zip = address_component.long_name;
      }
      break;
    }
    // console.log(address_component);

  }
  const geoLocation = {
    // The Lat/Lng values are defined from response "formatted address object" - uncomment live
    // lat: location.lat,
    // lng: location.lng,
    street: `${streetNumber} ${street}`,
    city,
    neighborhood,
    county,
    state,
    zip
  }
  console.log(geoLocation);

}


getMatchedTypes(address_components);

Clarification on Cloudinary example

Does the Cloudinary example store the image twice - once in the graphcool File type, and then a second time on the Cloudinary server? Thanks !

Unique slug generation

With the help of @kbrandwijk (thank you!), I've got a much more robust slug function that seems to be working well and handling every case (that I've thought of yet).

  1. It takes a title value from a new record, slugifies it (using slugs, rather than regex. Handles far more inputs - unicode, other language characters, etc.))
  2. then queries for a slug with the same value. If one exists, it appends -n+1 to the end. (e.g. title-of-post-1, title-of-post-2

I feel like this could be implemented as a schema extension as well, although I'm fairly new to that, so may be wrong.

It also needs to be adjusted heavily based on the particular project schema and naming etc.

'use latest';

const { GraphQLClient } = require('graphql-request')
const slugify = require('slugs')

const client = new GraphQLClient('__ENDPOINT__', {
  headers: {
    Authorization: 'Bearer __PAT-TOKEN__',
  }
})

module.exports = function (event) {
  // This query returns only the highest numbered slug (which could be the
  // only existing slug that may not have a trailing integer
  const query = `
    query($slug: String!) {
      allJobs(filter: {
        slug_starts_with: $slug
      }
      orderBy: slug_DESC
        first: 1
      ) {
        slug
      }
    }
  `

  const variables = {
    // Uses slugs to create slug - https://www.npmjs.com/package/slug
    slug: slugify(event.data.title)
  }

  return new Promise((resolve, reject) => {
    client.request(query, variables)
    .then(data => {
      let slug = variables.slug
      // If nothing comes back in the query, the slug doesn't already exist
      if (data.allJobs.length === 0) {
        const response = Object.assign({}, event.data, {slug})
        resolve({ data: response })
      } else {
        // Check the length of the returned result with the new slug to determine if there is
        // a trailing integer. If there isn't, use -2 or else create the next one.
        if (data.allJobs[0].slug.split('-').length === slug.split('-').length) {
         	slug = `${slug}-2`
        } else {
        	slug = `${slug}-${parseInt(data.allJobs[0].slug.split('-').pop()) + 1}`  
        }
        const response = Object.assign({}, event.data, {slug})
        resolve({ data: response })
      }
    })
    .catch(error => {
      console.log(error)
      reject(error)
    })
  })
}

I'm putting this in as an issue to look for guidance on whether this is worth writing up an including in these function examples. And should it be a Schema extension rather than a transform function?

Phone Auth Example

Currently following the steps for phone auth

When I get to this step it fails

Create a new Schema Extension Function called confirmUserSmsToken and paste the schema from confirm-code-schema-extension.graphql and code from sms-authentication.js.

This is the error that pops up

Function with name 'confirmUserSmsToken' has invalid payloadName: 'AuthenticateSmsUserPayload'

Function idea: subscriptions through push notifications

I just want to put this out here in case anyone else is also considering the same approach. The idea is that you would set up a SSS, and send the data as a Push notification.

So it would basically behave as a client side subscription, but instead of getting the results over an active wss connection, you would get the results as push notification, for when your app is not running.

Based on: https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/ (client-side) and https://github.com/web-push-libs/web-push (SSS-side) for browser, and similar platforms for mobile push notifications (for example: AWS SNS).

Slack Notification

var MY_SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/useyourownhere';
var slack = require('slack-notify')(MY_SLACK_WEBHOOK_URL);


module.exports = function (event) {
console.log(event.data.MyObject.node.myuserfield)
slack.send({
 text: ('Updated object: '+ event.data.myObject.node.myuserfield),
 unfurl_links: 1,
});
 
 
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.