Graphql with Azure functions - azure

is there a way to implement Graphql via azure functions and nodejs. For example, something like - https://www.npmjs.com/package/graphql-server-lambda

Apollo provides Azure Function Integration for GraphQL:
apollo-server-azure-functions
Here is the sample provided on their github repo:
const server = require("apollo-server-azure-functions");
const graphqlTools = require("graphql-tools");
const typeDefs = `
type Random {
id: Int!
rand: String
}
type Query {
rands: [Random]
rand(id: Int!): Random
}
`;
const rands = [{ id: 1, rand: "random" }, { id: 2, rand: "modnar" }];
const resolvers = {
Query: {
rands: () => rands,
rand: (_, { id }) => rands.find(rand => rand.id === id)
}
};
const schema = graphqlTools.makeExecutableSchema({
typeDefs,
resolvers
});
module.exports = function run(context, request) {
if (request.method === "POST") {
server.graphqlAzureFunctions({
endpointURL: '/api/graphql'
})(context, request);
} else if (request.method === "GET") {
return server.graphiqlAzureFunctions({
endpointURL: '/api/graphql'
})(context, request);
}
};

So I got this working using Apollo and Azure Functions. There is a mistake in the example for apollo-server-azure-functions, and a minor error in that wrapper library that returns string and not JSON data. You also need to install graphql-tools separately.
In the example code the schema object is created, but not added to the parameters passed to Apollo server. The working code is below. I've just added schema to the options passed.
const server = require("apollo-server-azure-functions");
const graphqlTools = require("graphql-tools");
const typeDefs = `
type Random {
id: Int!
rand: String
}
type Query {
rands: [Random]
rand(id: Int!): Random
}
`;
const rands = [{ id: 1, rand: "random" }, { id: 2, rand: "modnar" }];
const resolvers = {
Query: {
rands: () => rands,
rand: (_, { id }) => rands.find(rand => rand.id === id)
}
};
const schema = graphqlTools.makeExecutableSchema({
typeDefs,
resolvers
});
module.exports = function run(context, req) {
if (req.method === 'POST') {
server.graphqlAzureFunctions({
endpointURL: '/api/graphql',
schema: schema
})(context, req);
} else if (req.method === 'GET') {
return server.graphiqlAzureFunctions({
endpointURL: '/api/graphql',
schema: schema
})(context, req);
}
};
Just doing this change you will start to get data back from your endpoint, but unfortunately it will not be of type application/json. For that a small change needs to be made to apollo-server-azure-functions to convert the body from string to JSON. I've submitted a PR for this to happen, but not sure when they will get to it.
If you're not patient, you can create your own wrapper function with the code below which will work with the example above and return JSON not a string.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var apollo_server_core_1 = require("apollo-server-core");
var GraphiQL = require("apollo-server-module-graphiql");
function graphqlAzureFunctions(options) {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
throw new Error("Apollo Server expects exactly one argument, got " + arguments.length);
}
return function (httpContext, request) {
var queryRequest = {
method: request.method,
options: options,
query: request.method === 'POST' ? request.body : request.query,
};
if (queryRequest.query && typeof queryRequest.query === 'string') {
queryRequest.query = JSON.parse(queryRequest.query);
}
return apollo_server_core_1.runHttpQuery([httpContext, request], queryRequest)
.then(function (gqlResponse) {
var result = {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.parse(gqlResponse),
};
httpContext.res = result;
httpContext.done(null, result);
})
.catch(function (error) {
var result = {
status: error.statusCode,
headers: error.headers,
body: error.message,
};
httpContext.res = result;
httpContext.done(null, result);
});
};
}
exports.graphqlAzureFunctions = graphqlAzureFunctions;
function graphiqlAzureFunctions(options) {
return function (httpContext, request) {
var query = request.query;
GraphiQL.resolveGraphiQLString(query, options, httpContext, request).then(function (graphiqlString) {
httpContext.res = {
status: 200,
headers: {
'Content-Type': 'text/html',
},
body: graphiqlString,
};
httpContext.done(null, httpContext.res);
}, function (error) {
httpContext.res = {
status: 500,
body: error.message,
};
httpContext.done(null, httpContext.res);
});
};
}
exports.graphiqlAzureFunctions = graphiqlAzureFunctions;
For this to work you will need to install apollo-server-core and apollo-server-module-grapiql as dependencies via npm.

There's no native support for this, but there's nothing preventing you from creating a GraphQL schema that calls into Azure Functions.
However, there are some community offerings in the space like scaphold which work to integrate Azure Functions / serverless providers with GraphQL:
https://docs.scaphold.io/custom-logic/

For anyone looking to develop a GraphQL API with Typescript and Azure Functions, here's a starter repo you may consider: azure-function-graphql-typescript-starter (disclaimer: I'm the author)
It's built on top of:
Apollo Server
with Azure Functions integration
TypeGraphQL to make developing GraphQL APIs simple
and fun
PostgreSQL as persistence layer
TypeORM for database migrations and useful repository
classes

Related

Unable to get initial data using graphql-ws subscription

I am fairly new to using graphql-ws and graphql-yoga server, so forgive me if this is a naive question or mistake from my side.
I went through graphql-ws documentation. It has written the schema as a parameter. Unfortunately, the schema definition used in the documentation is missing a reference.
After adding a new todo (using addTodo) it shows two todo items. So I believe it is unable to return the initial todo list whenever running subscribe on Yoga Graphiql explorer.
It should show the initial todo item as soon as it has been subscribed and published in the schema definition.
My understanding is there is something I am missing in the schema definition which is not showing the todo list when tried accessing Yoga Graphiql explorer.
Has anyone had a similar experience and been able to resolve it? What I am missing?
Libraries used
Backend
graphql-yoga
ws
graphql-ws
Frontend
solid-js
wonka
Todo item - declared in schema
{
id: "1",
title: "Learn GraphQL + Solidjs",
completed: false
}
Screenshot
Code Snippets
Schema definition
import { createPubSub } from 'graphql-yoga';
import { Todo } from "./types";
let todos = [
{
id: "1",
title: "Learn GraphQL + Solidjs",
completed: false
}
];
// channel
const TODOS_CHANNEL = "TODOS_CHANNEL";
// pubsub
const pubSub = createPubSub();
const publishToChannel = (data: any) => pubSub.publish(TODOS_CHANNEL, data);
// Type def
const typeDefs = [`
type Todo {
id: ID!
title: String!
completed: Boolean!
}
type Query {
getTodos: [Todo]!
}
type Mutation {
addTodo(title: String!): Todo!
}
type Subscription {
todos: [Todo!]
}
`];
// Resolvers
const resolvers = {
Query: {
getTodos: () => todos
},
Mutation: {
addTodo: (_: unknown, { title }: Todo) => {
const newTodo = {
id: "" + (todos.length + 1),
title,
completed: false
};
todos.push(newTodo);
publishToChannel({ todos });
return newTodo;
},
Subscription: {
todos: {
subscribe: () => {
const res = pubSub.subscribe(TODOS_CHANNEL);
publishToChannel({ todos });
return res;
}
},
},
};
export const schema = {
resolvers,
typeDefs
};
Server backend
import { createServer } from "graphql-yoga";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";
import { schema } from "./src/schema";
import { execute, ExecutionArgs, subscribe } from "graphql";
async function main() {
const yogaApp = createServer({
schema,
graphiql: {
subscriptionsProtocol: 'WS', // use WebSockets instead of SSE
},
});
const server = await yogaApp.start();
const wsServer = new WebSocketServer({
server,
path: yogaApp.getAddressInfo().endpoint
});
type EnvelopedExecutionArgs = ExecutionArgs & {
rootValue: {
execute: typeof execute;
subscribe: typeof subscribe;
};
};
useServer(
{
execute: (args: any) => (args as EnvelopedExecutionArgs).rootValue.execute(args),
subscribe: (args: any) => (args as EnvelopedExecutionArgs).rootValue.subscribe(args),
onSubscribe: async (ctx, msg) => {
const { schema, execute, subscribe, contextFactory, parse, validate } =
yogaApp.getEnveloped(ctx);
const args: EnvelopedExecutionArgs = {
schema,
operationName: msg.payload.operationName,
document: parse(msg.payload.query),
variableValues: msg.payload.variables,
contextValue: await contextFactory(),
rootValue: {
execute,
subscribe,
},
};
const errors = validate(args.schema, args.document);
if (errors.length) return errors;
return args;
},
},
wsServer,
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
apply these changes
Mutation: {
addTodo: (_: unknown, { title }: Todo) => {
const newTodo = {
id: "" + (todos.length + 1),
title,
completed: false
};
todos.push(newTodo);
publishToChannel({ todos });
return newTodo;
},
Subscription: {
todos: {
subscribe: () => {
return Repeater.merge(
[
new Repeater(async (push, stop) => {
push({ todos });
await stop;
}),
pubSub.subscribe(TODOS_CHANNEL),
]
)
}
},
},
first, npm i #repeaterjs/repeater then import Repeater

FaunaDB returns empty array (FaunaDB + Netlify + VueJS)

My code is based on the repository - https://github.com/ttntm/recept0r-ts
Code from "\functions\read-all.js":
const faunadb = require('faunadb');
const fnHeaders = require('./_shared/headers.js');
exports.handler = (event, context) => {
const client = new faunadb.Client({
secret: process.env.FAUNA_SECRET,
domain: 'db.fauna.com',
scheme: 'https',
port: '443'
});
const q = faunadb.query;
const headers = { ...fnHeaders };
const origin = event.headers.Origin || event.headers.origin;
headers['Access-Control-Allow-Origin'] = origin ? origin : '*';
return client.query(q.Paginate(q.Match(q.Index('all_users'), false), { size: 500 }))
.then((response) => {
const listRefs = response.data;
const getListDataQuery = listRefs.map(ref => q.Get(ref)); // create new query out of list refs, then query the refs
return client.query(getListDataQuery).then((records) => {
return { statusCode: 200, headers: headers, body: JSON.stringify(records) }
})
})
.catch((error) => {
return { statusCode: 400, headers: headers, body: JSON.stringify(error) }
});
}
Code from "\src\store\modules\data.js":
async readAll({ commit, dispatch, rootGetters })
{
const fn = rootGetters['app/functions'];
const request = await fetch(fn.readAll, { method: 'GET' });
const response = await request.json();
if (response.length > 0) {
commit('SET_ALL_RECIPES', response);
commit('SET_LAST_UPDATED', new Date); }
else {
dispatch('app/sendToastMessage', { text: 'Error loading recipes. Please try again later.', type: 'error' }, { root: true });
return 'error';
}
}
Everything seems to be set. For example, this code works:
client.query(q.CreateCollection({ name: 'someCollection' }))
But can't read any data.
If launch application by "netlify dev" (localhost) - "read-all" returns empty array ("[]").
If launch application by "network" - "read-all" returns default "index.html".
I have no idea what's wrong. Maybe someone give advice...
I found a similar question - Local Netlify function server gives strange response instead of FaunaDB data
Some answer:
"In my experience, one of the most common reasons for this error is a routing problem, which is triggering a 404 response route serving HTML instead of your expected function handler."
This code works:
return client.query(q.Paginate(q.Documents(q.Collection('customers')), { size: 500 }))
.then((response) => {
const listRefs = response.data;
const getListDataQuery = listRefs.map(ref => q.Get(ref)); // create new query out of list refs, then query the refs
return client.query(getListDataQuery).then((records) => {
return { statusCode: 200, headers: headers, body: JSON.stringify(records) }
});
})
.catch((error) => {
return { statusCode: 400, headers: headers, body: JSON.stringify(error) }
});

NestJs: return modified response based on external API call

I am new to NestJs, Graphql, typescript.
I need to make an external API call which is basically Graphql query itself, modify the response if needed and return the response for the original request/query in this case test which is the query name.
I have the following code
#Query(returns => BlogPost) // #objectType
async test() {
const endpoint = 'https://testing.org/api/content/project-dev/graphql'
const graphQLClient = new GraphQLClient(endpoint, {
headers: {
authorization: 'Bearer xxxx',
},
})
const query = gql`
{
queryContentContentsWithTotal(top: 10) {
total
}
}`
const data = await graphQLClient.request(query)
console.log(JSON.stringify(data, undefined, 2))
return data;
}
The BlogPost is the ObjectType which looks like :
import { Field, ObjectType } from '#nestjs/graphql';
#ObjectType()
export class BlogPost {
#Field({ nullable: true })
total!: number;
}
I have placed console.log as well to see the external API call response which is:
{
"queryContentContentsWithTotal": {
"total": 1
}
}
but the Graphql response for the query is :
{
"data": {
"test": {
"total": null // this needs to be 1
}
}
}
total is null where the API call returns total value 1;
How can be the mapping done with flexibility here so that the query response looks the same?
GraphQL is expecting your return data in the shape of
{
"total": "number of some sort"
}
But you're actually returning data in the shape of
{
"queryContentContentsWithTotal": {
"total": 1
}
}
So the GraphQL engine can't understand the return type. You need to map your data to the proper return like so:
#Query(returns => BlogPost) // #objectType
async test() {
const endpoint = 'https://testing.org/api/content/project-dev/graphql'
const graphQLClient = new GraphQLClient(endpoint, {
headers: {
authorization: 'Bearer xxxx',
},
})
const query = gql`
{
queryContentContentsWithTotal(top: 10) {
total
}
}`
const data = await graphQLClient.request(query)
console.log(JSON.stringify(data, undefined, 2))
return data.queryContentContentsWithTotal;
}
You are returning data which is not the same type as BlogPost. You should return this instead
return {total: data.queryContentContentsWithTotal.total}

Pass Object to Node JS GET request

I am trying to pass an object to my NodeJS server from my angular application. I can read the object perfectly fine on the client-side, but not serverside.
Here is my client-side:
var query = {
date: '9-2-2019',
size: 4
}
this.http.get<any>(url, {params: {query: query} }).toPromise();
Why can I not pass this to my Node JS server?
No overload matches this call.
Is my error.
Please change { params: {query: query}} to be {params: query} and also change query.size to be string instead of number
var query = {
date: '9-2-2019',
size: '4'
}
this.http.get<any>(url, {params: query}).toPromise().then(response => {
console.log(response);
})
.catch(console.log);
Alternative
Create // utils.service.ts
import { HttpParams } from '#angular/common/http';
// ...
export class UtilsService {
static buildQueryParams(source: Object): HttpParams {
let target: HttpParams = new HttpParams();
Object.keys(source).forEach((key: string) => {
const value: string | number | boolean | Date = source[key];
if ((typeof value !== 'undefined') && (value !== null)) {
target = target.append(key, value.toString());
}
});
return target;
}
}
then use it in your service
import { UtilsService } from '/path/to/utils.service';
var query = {
date: '9-2-2019',
size: 4
}
const queryParams: HttpParams = UtilsService.buildQueryParams(query);
this.http.get<any>(url, {params: queryParams }).toPromise().then(response => {
console.log(response);
})
.catch(console.log);

Call server-side function from ReactJS component

I'm trying to implement a payments system in my ReactJS app that requires server-side code.
I have several questions:
How do you connect a ReactJS app so it can communicate with server-side code?
How would you set up a function in the server-side code?
How would you call that function from a component in a ReactJS app?
For reference, I'm trying to integrate Stripe subscriptions. They give server-side code examples for Node, PHP, etc.
FYI: I am not trying to set up server-side rendering. When you search for server-side code in reference to ReactJS, that's just about all that comes up.
EDIT: I'm particularly interested in a NodeJS solution. I'm also using Webpack.
Just in case, it is helpful to you... I have a React UI that triggers video processing on a Django backend (I mainly use GraphQL through Apollo Client to trigger my server side functions and REST framework when file transfers are involved).
Is REST an option for you?
The middleware I use for file transfers for example:
const SERVER_URL = process.env.SERVER_URL;
const fileTransferApi = (payload) => {
const { authenticated, token, endpoint, body, contentType, method } = payload;
let config = {};
if (authenticated) {
if (token) {
config = {
method,
headers: {
'Content-Type': contentType,
Authorization: `Bearer ${token}`
},
body
};
} else {
throw new Error('No token saved!');
}
}
return fetch(`${SERVER_URL}/api/rest/v1/${endpoint}`, config)
.then((response) =>
response.text().then((text) => ({ text, response }))
).then(({ text, response }) => {
if (!response.ok) {
return Promise.reject(text);
}
return text;
}).catch((err) => console.log(err));
};
export const FILE_TRANSFER_API = Symbol('FILE_TRANSFER_API');
export default () => (next) => (action) => {
const fileTransferApiAction = action[FILE_TRANSFER_API];
if (typeof fileTransferApiAction === 'undefined') {
return next(action);
}
const { payload, types } = fileTransferApiAction;
const [, successType, errorType] = types;
return fileTransferApi(payload).then(
(response) =>
next({
type: successType,
payload: {
text: response,
message: 'ok'
}
}),
(error) => next({
type: errorType,
payload: {
error: error.message || 'There was an error.'
}
})
);
};
My store (I use Redux):
import { createStore, compose, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import ReduxThunk from 'redux-thunk';
import ApolloClientSingleton from '../network/apollo-client-singleton';
import fileTransferApi from '../middlewares/fileTransferApi';
import reducer from './reducers';
export default class Store {
constructor(history, initialState = {}) {
this.data = createStore(
reducer,
initialState,
compose(
applyMiddleware(
fileTransferApi,
ReduxThunk.withExtraArgument(ApolloClientSingleton),
routerMiddleware(history),
ApolloClientSingleton.middleware()
),
typeof window === 'object' && typeof window.devToolsExtension !== 'undefined'
? window.devToolsExtension() : (f) => f
)
);
}
}
In my actions:
export const windowsDownload = (authenticated, token) => ({
[FILE_TRANSFER_API]: {
types: [WINDOW_DOWNLOAD_REQUEST, WINDOW_DOWNLOAD_SUCCESS, WINDOW_DOWNLOAD_FAILURE],
payload: {
endpoint: 'file_transfer/download/windows',
contentType: 'text/csv',
method: 'get',
body: null,
authenticated,
token
}
}
});
This REST setup enables me to send requests (POST video, GET csv...) from my React UI to my Django server. Can't you set up some REST calls between your app and your server?

Resources