Skip to content

Instantly share code, notes, and snippets.

@sapher
Last active May 25, 2017 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sapher/522a9fea5b7c55f51d5a8766e566e3c6 to your computer and use it in GitHub Desktop.
Save sapher/522a9fea5b7c55f51d5a8766e566e3c6 to your computer and use it in GitHub Desktop.
AWS Lambda (use lambda proxy) for registering FCM refresh token to AWS SNS
const AWS = require('aws-sdk');
const SnsClient = new AWS.SNS();
const createEndpoint = (platformAppArn, token, callback) => {
const createParams = {
PlatformApplicationArn: platformAppArn,
Token: token
};
SnsClient.createPlatformEndpoint(createParams, (err, data) => {
if(err) {
return callback(err);
}
else {
const endpointArn = data.EndpointArn;
const res = {
statusCode: 200,
headers: {},
body: JSON.stringify({ app_token : endpointArn })
};
return callback(null, res);
}
});
};
exports.handler = (event, context, callback) => {
// Application ARN is passed as ENVironnement variable
const appArn = process.env.SNS_APP_ARN;
// Get body from request
let body = event["body"];
// parse local data
if(typeof body === "string") {
body = JSON.parse(body);
}
// Retrieve useful data
const refreshToken = body['refresh_token'];
let appToken = body['app_token'];
// easier
const endpointArn = appToken;
// First time registration, create endpoint
if(!appToken) {
createEndpoint(appArn, refreshToken, callback);
}
// Already created
else {
// Get attributes
SnsClient.getEndpointAttributes({ EndpointArn: endpointArn }, (err, data) => {
// not found or issue, assume we need to recreate
if(err) {
createEndpoint(appArn, refreshToken, callback);
}
// endpoint found
else {
const update = data.Attributes.Token !== refreshToken || data.Attributes.Enabled !== true;
// need update
if(update) {
const updateParams = {
EndpointArn: endpointArn,
Attributes: {
Token: refreshToken,
Enabled: "true"
}
};
SnsClient.setEndpointAttributes(updateParams, (err, data) => {
if(err) return callback(err);
else {
const res = {
statusCode: 200,
headers: {},
body: JSON.stringify({})
};
return callback(null, res);
}
});
}
// no update needed, we can go
else {
const res = {
statusCode: 200,
headers: {},
body: JSON.stringify({})
};
return callback(null, res);
}
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment