Rhett  Bosco

Rhett Bosco

1604730733

How to Integrate TypeScript into Twilio Functions Project to Send an SMS

Learn about TypeScript and how to integrate it into a Twilio Functions project to send an SMS.

Sometimes, when cost, resources, and time-to-market are factors, it can be worth considering going the serverless route. And, if a development team has decided upon a Node.js stack for the back-end, the benefits of TypeScript are enormous for safety, developer productivity, and new developer onboarding.

TypeScript is an extension of pure JavaScript - a “superset”, if you will - and adds static typing to the language. It enforces type safety, makes code easier to reason about, and permits the implementation of classic patterns in a more “traditional” manner. As a language extension, all JavaScript is valid TypeScript, and TypeScript is compiled down to JavaScript.

With Twilio Functions, you can easily create “serverless” applications that are natively integrated with the Twilio ecosystem. That means support for SMS messages, for example, is first-class. You won’t have to manage infrastructure or provision servers, and you can very quickly move from development to production.

In this tutorial, you’ll learn how to integrate Twilio Functions with TypeScript and send SMS messages via the Twilio Programmable SMS API.

Requirements

  • Node.js 10 - Consider using a tool like nvm to manage Node.js versions.
  • A Twilio Account with an SMS-capable phone number. If you are new to Twilio, you can create a free account and register a number.

Project Configuration

The Twilio CLI will permit you to manage Twilio resources from the command line. It can be extended by plugins, one of which is the Twilio Serverless Toolkit. The Serverless Toolkit adds CLI functionality to develop functions, among other things, locally and deploy them to the Twilio Runtime.

To begin, utilize the Twilio Serverless Toolkit via the Twilio CLI to scaffold a boilerplate. Install and authenticate with the required dependencies and plugins:

npm i -g twilio-cli
twilio plugins:install @twilio-labs/plugin-serverless
twilio-login

The twilio-login command will prompt you for your account credentials which can be found on your Twilio Console dashboard.

Next, bootstrap a boilerplate. In the command below, init will initialize a JavaScript project within a folder called ts-sms-demo (as specified) containing multiple stock/example files and directories.

twilio serverless:init ts-sms-demo
cd ts-sms-demo

In this post, by creating the project in this manner, you’ll end up retrofitting an existing JavaScript-based project to work with TypeScript (because the CLI creates a JavaScript project by default). If, instead, you want to start from scratch with TypeScript, you can swap out the init command above to: twilio serverless:init ts-sms-demo --typescript, and a TypeScript project will be bootstrapped.

You should now have a new directory with the name ts-sms-demo. After navigating inside, you’ll see a few default files and directories:

A view of the default boilerplate created by the Serverless Tooklit.

At this point, after running npm start, you can navigate your browser to http://localhost:3000 where the index page will walk you through the different files and folders. For this project, you’ll be most interested in the functions directory, but you’ll have to do a little configuration to achieve full interoperability with TypeScript.

Setting up TypeScript

This article covers converting a pre-initialized JavaScript project over to TypeScript. If you’re looking for a more in-depth resource regarding TypeScript configuration or moving a large JS project over to TS, take a look at Dominik Kundel’s article How to move your project to TypeScript - at your own pace.

You’ll install the TypeScript compiler and save it as a development dependency - it’s important to note that the tooling and functionality provided by TypeScript and the TypeScript compiler are available only at compile time - everything TypeScript specific is lost in the built JavaScript code post-compilation:

npm install typescript --save-dev

Using the installed TypeScript compiler, you’ll need to create a_ tsconfig.json_ file at the root of the project. The configuration parameters you specify within this file will affect the compilation process. Create the file by utilizing tsc - the compiler you installed above. From the root of the project, run the following command:

node_modules/.bin/tsc --init

Open the file, and clear its contents. We need to do a few things here - first, we’ll specify the compilation target and module system for the built code. Next, we’ll point the compiler to the root directory containing our TypeScript source code.

The compiler will take these files, compile them to JavaScript, and output them into an “out” directory, which we’ll also specify. Finally, as a method of “defensive coding”, we’ll enable “strict” mode, which specifies how strict the compiler should be when performing type checking.

  • target specifies which particular target of JavaScript should be emitted during compilation, and you can denote it via ECMAScript versions. For more information, visit the relevant section of the TypeScript Documentation.
  • module sets the module system, such as “CommonJS”, “UMD”, “AMD”, etc. The TypeScript documentation defines this in more detail here and here.

Make the following the new contents of your tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES5",        
    "module": "commonjs",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

The most important parts to us are outDir and rootDir. Relative to the root directory (the root project directory, that is), we’ve specified that we wish for the compiler to compile all TypeScript source files in the src folder and output the built JavaScript into another folder, also relative to root, called build. The compiler will preserve the directory structure from src within build. This is going to be important because we’ll need to specify to the Twilio CLI where our functions will live.

To test this, create a folder called src in your root directory. Inside of that folder, create another folder entitled functions, and place a TypeScript file inside:

mkdir src
mkdir src/functions
touch src/functions/hello-world.ts

Now, in your terminal, run the TypeScript compiler:

node_modules/.bin/tsc

Within your project directory, you should see that a build folder has been created, and within that folder should be a one-to-one mapping of your src directories, except the files within have been compiled to JavaScript. I deleted the top-level assets and functions folders to make this easier to see, and you should do the same.

A view of the TypeScript source file and the output.

We can use the fact that the folder structure is preserved to specify to the Twilio CLI where the functions will live. We’ll write the function in TypeScript under src/functions, and then we’ll use the --functions-folder flag to state that the compiled functions will live under ./build/functions. Make the required changes to package.json now:

{
  "name": "ts-sms-demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "prestart": "tsc",
    "start": "twilio-run start --functions-folder ./build/functions",
    "predeploy": "tsc",
    "deploy": "twilio-run deploy --functions-folder ./build/functions"
  },
  "dependencies": {},
  "devDependencies": {
    "twilio-run": "^2.6.0",
    "typescript": "^4.0.5"
  },
  "engines": {
    "node": "10"
  }
}

Prefixing script names with pre or post, as in prestart and predeploy, creates a “lifecycle” around the script, if you will. In this case, when running npm start, the contents of prestart will be executed as well. The same goes for deploy and predeploy.

By default, the Twilio Runtime looks inside the root functions folder for functions. Since we’re using TypeScript, and since we may want to use other TypeScript files within our functions, we use the Serverless Toolkit’s --functions-folder flag to override the default behavior and specify a new location where the functions can be found. That’s the build/functions folder in our case.

Testing a TypeScript Function

It took a little bit of work, but you’re now ready to create your first TypeScript Function. If you haven’t already done so, go ahead and delete the top-level build, assets, and functions folders. We’ll be working within src, so navigate inside and create a functions folder (which you might already have from the example above).

There, create a file called_ hello-world.ts_. We’ll test that you can build and deploy TypeScript functions by displaying “Hello, World!” to the client. Add the following function to hello-world.ts:

export const handler = (context, event, callback) => {
    return callback(null, 'Hello, World!');
}
  • context contains runtime specific properties, including a factory function that returns an initialized Twilio Client.
  • event contains properties pertaining to function invocations, such as a body or parameters passed up from an incoming HTTP Request.
  • callback returns execution control to the runtime - it accepts nullable error information and an optional response payload.

If you attempt to compile the project now with tsc command at the root of the project, you will immediately be met with errors - that’s because TypeScript does not know the expected types of context, event, and callback. This is a feature of “strict” mode, which we enabled earlier.

Although it may seem counterintuitive to explicitly state that we wish to have more possibilities for errors, these errors will help us to ensure that we are receiving the full benefits of TypeScript. We can rectify the issues either by explicitly typing the three parameters or explicitly providing handler with a type for a function signature.

Contrary to how most typing packages are usually installed (via Definitely Typed), types for Twilio Functions live within a twilio-labs package, which you can install as follows:

npm install --save-dev @twilio-labs/serverless-runtime-types

For the context parameter, the Context type is used, for callback, the ServerlessCallback type is used. These are both available as named exports from @twilio-labs/serverless-runtime-types/types.

The event parameter can be typed manually via an interface or type alias to contain the types that you expect as per the request parameters or POST body defined for the function.

In this case, rather than explicitly typing all three parameters, you’ll use ServerlessFunctionSignature to type handler, which will permit TypeScript to infer the parameters automatically as those types I mentioned above:

import { ServerlessFunctionSignature } from '@twilio-labs/serverless-runtime-types/types';

export const handler: ServerlessFunctionSignature = (context, event, callback) => {
    return callback(null, 'Hello, World!');
}

At this point, you should be able to run npm start. TSC will compile your TypeScript source code and your function should be available via the Twilio Runtime on localhost. The name of the file specifies the location of the function in the URI, so in our case, the function is available at http://locahost:3000/hello-world.

Let’s make a GET Request to the function and ensure we get a “Hello, World!” response back:

curl http://localhost:3000/hello-world ## -> Hello, World!

With that working, we can now integrate Twilio SMS.

Integrating Twilio Programmable SMS

If you don’t already have one, create a free Twilio account and purchase a trial number with SMS capabilities. New Twilio accounts are provided with a 15 USD free credit, so you can complete this tutorial without having to purchase any services. Ensure the phone number has SMS capabilities for your specific region, and if not, enable permissions here.

Using the context object, you can gain access to a pre-initialized Twilio client instance since the Twilio Runtime is aware of your Account SID and Auth Token.

Using this object, you can access the Twilio SMS REST API, which is wrapped by the client. You can go ahead and make the function asynchronous, and then you’ll send an SMS message, specifying a message body, your Twilio phone number, and a target (receiving) phone number:

import { ServerlessFunctionSignature } from '@twilio-labs/serverless-runtime-types/types';

export const handler: ServerlessFunctionSignature = async (context, event, callback) => {
    const twilioClient = context.getTwilioClient();

    try {
        await twilioClient.messages.create({
            body: 'Hello, World from Twilio Functions with TypeScript',
            to: '[Your Phone Number (Format: +11234567890)]',
            from: '[Your Twilio Phone Number (Format: +11234567890)]'
        });

        return callback(null);
    } catch (e) {
        return callback(e);
    }
}

You don’t necessarily have to await the promise settling result of sending the message, but since we are, we’ll wrap the operation in a try/catch block.

If the message is sent correctly, we’ll call the callback, passing null as the first parameter since we don’t have an error object. Otherwise, we’ll pass that error object along. Calling callback ends the request, so you can’t afford not to call it, otherwise, the request will hang.

If you have multiple functions, I’d recommend not repeating the try/catch block everywhere, and opting instead for some kind of withErrorHandling higher-order function that encapsulates your asynchronous and transient requests, watches for errors, and handles them accordingly. This would be considered more “DRY”.

If you run npm start and then make a GET Request to your function, as above (curl [http://localhost:3000/hello-world](http://localhost:3000/hello-world)), your target phone number will receive an SMS message after a short delay.

Deploying your Function

With the function developed and working locally, all you have to now is deploy it with:

npm run deploy

This will fire the predeploy hook to re-compile the project, and then the runtime will use the build/functions files as your functions. Your function URL will be of the form: https://ts-sms-demo-[identifier]-dev.twil.io/hello-world.

Conclusion

We’ve now gone through the process of making TypeScript compatible with Twilio Functions and integrated SMS. Consider taking the project a little further by researching how to make your function respond to POST requests and capture SMS messages from users.

Additionally, taking the following steps may be desirable:

  • Add the build/ directory to your .gitignore so that we can keep the compiled JavaScript out of any git repositories.
  • Consider taking approaches to consolidate error handling so you don’t have to constantly repeat try/catch in your functions.
  • Take a look at the Twilio Functions and Serverless Toolkit documentation.

The Original Article can be found on twilio.com

#typescript #twilio #programming #javascript #web-development

What is GEEK

Buddha Community

How to Integrate TypeScript into Twilio Functions Project to Send an SMS
Aketch  Rachel

Aketch Rachel

1618053060

How to send SMS with Twilio in ASP.NET Core 5 and C#

How to Send an SMS with ASP.NET Core

Let’s get started with setting up a Twilio SMS account. When we create a Twilio account, we are going to be given a free trial account with a 15.50 USD. We can use the trial balance toward purchasing a phone number and sending and receiving messages.

#c# #dotnet core #how to #send sms with twilio #twilio send sms #using twilio to send sms

Autumn  Blick

Autumn Blick

1593867420

Top Android Projects with Source Code

Android Projects with Source Code – Your entry pass into the world of Android

Hello Everyone, welcome to this article, which is going to be really important to all those who’re in dilemma for their projects and the project submissions. This article is also going to help you if you’re an enthusiast looking forward to explore and enhance your Android skills. The reason is that we’re here to provide you the best ideas of Android Project with source code that you can choose as per your choice.

These project ideas are simple suggestions to help you deal with the difficulty of choosing the correct projects. In this article, we’ll see the project ideas from beginners level and later we’ll move on to intermediate to advance.

top android projects with source code

Android Projects with Source Code

Before working on real-time projects, it is recommended to create a sample hello world project in android studio and get a flavor of project creation as well as execution: Create your first android project

Android Projects for beginners

1. Calculator

build a simple calculator app in android studio source code

Android Project: A calculator will be an easy application if you have just learned Android and coding for Java. This Application will simply take the input values and the operation to be performed from the users. After taking the input it’ll return the results to them on the screen. This is a really easy application and doesn’t need use of any particular package.

To make a calculator you’d need Android IDE, Kotlin/Java for coding, and for layout of your application, you’d need XML or JSON. For this, coding would be the same as that in any language, but in the form of an application. Not to forget creating a calculator initially will increase your logical thinking.

Once the user installs the calculator, they’re ready to use it even without the internet. They’ll enter the values, and the application will show them the value after performing the given operations on the entered operands.

Source Code: Simple Calculator Project

2. A Reminder App

Android Project: This is a good project for beginners. A Reminder App can help you set reminders for different events that you have throughout the day. It’ll help you stay updated with all your tasks for the day. It can be useful for all those who are not so good at organizing their plans and forget easily. This would be a simple application just whose task would be just to remind you of something at a particular time.

To make a Reminder App you need to code in Kotlin/Java and design the layout using XML or JSON. For the functionality of the app, you’d need to make use of AlarmManager Class and Notifications in Android.

In this, the user would be able to set reminders and time in the application. Users can schedule reminders that would remind them to drink water again and again throughout the day. Or to remind them of their medications.

3. Quiz Application

Android Project: Another beginner’s level project Idea can be a Quiz Application in android. Here you can provide the users with Quiz on various general knowledge topics. These practices will ensure that you’re able to set the layouts properly and slowly increase your pace of learning the Android application development. In this you’ll learn to use various Layout components at the same time understanding them better.

To make a quiz application you’ll need to code in Java and set layouts using xml or java whichever you prefer. You can also use JSON for the layouts whichever preferable.

In the app, questions would be asked and answers would be shown as multiple choices. The user selects the answer and gets shown on the screen if the answers are correct. In the end the final marks would be shown to the users.

4. Simple Tic-Tac-Toe

android project tic tac toe game app

Android Project: Tic-Tac-Toe is a nice game, I guess most of you all are well aware of it. This will be a game for two players. In this android game, users would be putting X and O in the given 9 parts of a box one by one. The first player to arrange X or O in an adjacent line of three wins.

To build this game, you’d need Java and XML for Android Studio. And simply apply the logic on that. This game will have a set of three matches. So, it’ll also have a scoreboard. This scoreboard will show the final result at the end of one complete set.

Upon entering the game they’ll enter their names. And that’s when the game begins. They’ll touch one of the empty boxes present there and get their turn one by one. At the end of the game, there would be a winner declared.

Source Code: Tic Tac Toe Game Project

5. Stopwatch

Android Project: A stopwatch is another simple android project idea that will work the same as a normal handheld timepiece that measures the time elapsed between its activation and deactivation. This application will have three buttons that are: start, stop, and hold.

This application would need to use Java and XML. For this application, we need to set the timer properly as it is initially set to milliseconds, and that should be converted to minutes and then hours properly. The users can use this application and all they’d need to do is, start the stopwatch and then stop it when they are done. They can also pause the timer and continue it again when they like.

6. To Do App

Android Project: This is another very simple project idea for you as a beginner. This application as the name suggests will be a To-Do list holding app. It’ll store the users schedules and their upcoming meetings or events. In this application, users will be enabled to write their important notes as well. To make it safe, provide a login page before the user can access it.

So, this app will have a login page, sign-up page, logout system, and the area to write their tasks, events, or important notes. You can build it in android studio using Java and XML at ease. Using XML you can build the user interface as user-friendly as you can. And to store the users’ data, you can use SQLite enabling the users to even delete the data permanently.

Now for users, they will sign up and get access to the write section. Here the users can note down the things and store them permanently. Users can also alter the data or delete them. Finally, they can logout and also, login again and again whenever they like.

7. Roman to decimal converter

Android Project: This app is aimed at the conversion of Roman numbers to their significant decimal number. It’ll help to check the meaning of the roman numbers. Moreover, it will be easy to develop and will help you get your hands on coding and Android.

You need to use Android Studio, Java for coding and XML for interface. The application will take input from the users and convert them to decimal. Once it converts the Roman no. into decimal, it will show the results on the screen.

The users are supposed to just enter the Roman Number and they’ll get the decimal values on the screen. This can be a good android project for final year students.

8. Virtual Dice Roller

Android Project: Well, coming to this part that is Virtual Dice or a random no. generator. It is another simple but interesting app for computer science students. The only task that it would need to do would be to generate a number randomly. This can help people who’re often confused between two or more things.

Using a simple random number generator you can actually create something as good as this. All you’d need to do is get you hands-on OnClick listeners. And a good layout would be cherry on the cake.

The user’s task would be to set the range of the numbers and then click on the roll button. And the app will show them a randomly generated number. Isn’t it interesting ? Try soon!

9. A Scientific Calculator App

Android Project: This application is very important for you as a beginner as it will let you use your logical thinking and improve your programming skills. This is a scientific calculator that will help the users to do various calculations at ease.

To make this application you’d need to use Android Studio. Here you’d need to use arithmetic logics for the calculations. The user would need to give input to the application that will be in terms of numbers. After that, the user will give the operator as an input. Then the Application will calculate and generate the result on the user screen.

10. SMS App

Android Project: An SMS app is another easy but effective idea. It will let you send the SMS to various no. just in the same way as you use the default messaging application in your phone. This project will help you with better understanding of SMSManager in Android.

For this application, you would need to implement Java class SMSManager in Android. For the Layout you can use XML or JSON. Implementing SMSManager into the app is an easy task, so you would love this.

The user would be provided with the facility to text to whichever number they wish also, they’d be able to choose the numbers from the contact list. Another thing would be the Textbox, where they’ll enter their message. Once the message is entered they can happily click on the send button.

#android tutorials #android application final year project #android mini projects #android project for beginners #android project ideas #android project ideas for beginners #android projects #android projects for students #android projects with source code #android topics list #intermediate android projects #real-time android projects

I am Developer

1613800156

Laravel 8 Send SMS to Mobile with Nexmo Tutorial

Laravel 8 send sms using nexmo example. In this tutorial, you will learn how to integrate sms gateway and send sms notification to mobile using nexmo in laravel 8 app.

This tutorial will guide you step by step on how to send send sms to mobile with nexmo in laravel 8 app. Now, You need to follow the some step to done laravel nexmo message.

First of all, visit the following link https://dashboard.nexmo.com/sign-in and create nexmo account. Get client id and secret from nexom account.

https://www.tutsmake.com/laravel-8-send-sms-to-mobile-with-nexmo-example/

#send sms with nexmo on laravel #nexmo message send sms #laravel send sms notification #nexmo sms installation laravel #how to integrate sms gateway in laravel

Rhett  Bosco

Rhett Bosco

1604730733

How to Integrate TypeScript into Twilio Functions Project to Send an SMS

Learn about TypeScript and how to integrate it into a Twilio Functions project to send an SMS.

Sometimes, when cost, resources, and time-to-market are factors, it can be worth considering going the serverless route. And, if a development team has decided upon a Node.js stack for the back-end, the benefits of TypeScript are enormous for safety, developer productivity, and new developer onboarding.

TypeScript is an extension of pure JavaScript - a “superset”, if you will - and adds static typing to the language. It enforces type safety, makes code easier to reason about, and permits the implementation of classic patterns in a more “traditional” manner. As a language extension, all JavaScript is valid TypeScript, and TypeScript is compiled down to JavaScript.

With Twilio Functions, you can easily create “serverless” applications that are natively integrated with the Twilio ecosystem. That means support for SMS messages, for example, is first-class. You won’t have to manage infrastructure or provision servers, and you can very quickly move from development to production.

In this tutorial, you’ll learn how to integrate Twilio Functions with TypeScript and send SMS messages via the Twilio Programmable SMS API.

Requirements

  • Node.js 10 - Consider using a tool like nvm to manage Node.js versions.
  • A Twilio Account with an SMS-capable phone number. If you are new to Twilio, you can create a free account and register a number.

Project Configuration

The Twilio CLI will permit you to manage Twilio resources from the command line. It can be extended by plugins, one of which is the Twilio Serverless Toolkit. The Serverless Toolkit adds CLI functionality to develop functions, among other things, locally and deploy them to the Twilio Runtime.

To begin, utilize the Twilio Serverless Toolkit via the Twilio CLI to scaffold a boilerplate. Install and authenticate with the required dependencies and plugins:

npm i -g twilio-cli
twilio plugins:install @twilio-labs/plugin-serverless
twilio-login

The twilio-login command will prompt you for your account credentials which can be found on your Twilio Console dashboard.

Next, bootstrap a boilerplate. In the command below, init will initialize a JavaScript project within a folder called ts-sms-demo (as specified) containing multiple stock/example files and directories.

twilio serverless:init ts-sms-demo
cd ts-sms-demo

In this post, by creating the project in this manner, you’ll end up retrofitting an existing JavaScript-based project to work with TypeScript (because the CLI creates a JavaScript project by default). If, instead, you want to start from scratch with TypeScript, you can swap out the init command above to: twilio serverless:init ts-sms-demo --typescript, and a TypeScript project will be bootstrapped.

You should now have a new directory with the name ts-sms-demo. After navigating inside, you’ll see a few default files and directories:

A view of the default boilerplate created by the Serverless Tooklit.

At this point, after running npm start, you can navigate your browser to http://localhost:3000 where the index page will walk you through the different files and folders. For this project, you’ll be most interested in the functions directory, but you’ll have to do a little configuration to achieve full interoperability with TypeScript.

Setting up TypeScript

This article covers converting a pre-initialized JavaScript project over to TypeScript. If you’re looking for a more in-depth resource regarding TypeScript configuration or moving a large JS project over to TS, take a look at Dominik Kundel’s article How to move your project to TypeScript - at your own pace.

You’ll install the TypeScript compiler and save it as a development dependency - it’s important to note that the tooling and functionality provided by TypeScript and the TypeScript compiler are available only at compile time - everything TypeScript specific is lost in the built JavaScript code post-compilation:

npm install typescript --save-dev

Using the installed TypeScript compiler, you’ll need to create a_ tsconfig.json_ file at the root of the project. The configuration parameters you specify within this file will affect the compilation process. Create the file by utilizing tsc - the compiler you installed above. From the root of the project, run the following command:

node_modules/.bin/tsc --init

Open the file, and clear its contents. We need to do a few things here - first, we’ll specify the compilation target and module system for the built code. Next, we’ll point the compiler to the root directory containing our TypeScript source code.

The compiler will take these files, compile them to JavaScript, and output them into an “out” directory, which we’ll also specify. Finally, as a method of “defensive coding”, we’ll enable “strict” mode, which specifies how strict the compiler should be when performing type checking.

  • target specifies which particular target of JavaScript should be emitted during compilation, and you can denote it via ECMAScript versions. For more information, visit the relevant section of the TypeScript Documentation.
  • module sets the module system, such as “CommonJS”, “UMD”, “AMD”, etc. The TypeScript documentation defines this in more detail here and here.

Make the following the new contents of your tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES5",        
    "module": "commonjs",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

The most important parts to us are outDir and rootDir. Relative to the root directory (the root project directory, that is), we’ve specified that we wish for the compiler to compile all TypeScript source files in the src folder and output the built JavaScript into another folder, also relative to root, called build. The compiler will preserve the directory structure from src within build. This is going to be important because we’ll need to specify to the Twilio CLI where our functions will live.

To test this, create a folder called src in your root directory. Inside of that folder, create another folder entitled functions, and place a TypeScript file inside:

mkdir src
mkdir src/functions
touch src/functions/hello-world.ts

Now, in your terminal, run the TypeScript compiler:

node_modules/.bin/tsc

Within your project directory, you should see that a build folder has been created, and within that folder should be a one-to-one mapping of your src directories, except the files within have been compiled to JavaScript. I deleted the top-level assets and functions folders to make this easier to see, and you should do the same.

A view of the TypeScript source file and the output.

We can use the fact that the folder structure is preserved to specify to the Twilio CLI where the functions will live. We’ll write the function in TypeScript under src/functions, and then we’ll use the --functions-folder flag to state that the compiled functions will live under ./build/functions. Make the required changes to package.json now:

{
  "name": "ts-sms-demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "prestart": "tsc",
    "start": "twilio-run start --functions-folder ./build/functions",
    "predeploy": "tsc",
    "deploy": "twilio-run deploy --functions-folder ./build/functions"
  },
  "dependencies": {},
  "devDependencies": {
    "twilio-run": "^2.6.0",
    "typescript": "^4.0.5"
  },
  "engines": {
    "node": "10"
  }
}

Prefixing script names with pre or post, as in prestart and predeploy, creates a “lifecycle” around the script, if you will. In this case, when running npm start, the contents of prestart will be executed as well. The same goes for deploy and predeploy.

By default, the Twilio Runtime looks inside the root functions folder for functions. Since we’re using TypeScript, and since we may want to use other TypeScript files within our functions, we use the Serverless Toolkit’s --functions-folder flag to override the default behavior and specify a new location where the functions can be found. That’s the build/functions folder in our case.

Testing a TypeScript Function

It took a little bit of work, but you’re now ready to create your first TypeScript Function. If you haven’t already done so, go ahead and delete the top-level build, assets, and functions folders. We’ll be working within src, so navigate inside and create a functions folder (which you might already have from the example above).

There, create a file called_ hello-world.ts_. We’ll test that you can build and deploy TypeScript functions by displaying “Hello, World!” to the client. Add the following function to hello-world.ts:

export const handler = (context, event, callback) => {
    return callback(null, 'Hello, World!');
}
  • context contains runtime specific properties, including a factory function that returns an initialized Twilio Client.
  • event contains properties pertaining to function invocations, such as a body or parameters passed up from an incoming HTTP Request.
  • callback returns execution control to the runtime - it accepts nullable error information and an optional response payload.

If you attempt to compile the project now with tsc command at the root of the project, you will immediately be met with errors - that’s because TypeScript does not know the expected types of context, event, and callback. This is a feature of “strict” mode, which we enabled earlier.

Although it may seem counterintuitive to explicitly state that we wish to have more possibilities for errors, these errors will help us to ensure that we are receiving the full benefits of TypeScript. We can rectify the issues either by explicitly typing the three parameters or explicitly providing handler with a type for a function signature.

Contrary to how most typing packages are usually installed (via Definitely Typed), types for Twilio Functions live within a twilio-labs package, which you can install as follows:

npm install --save-dev @twilio-labs/serverless-runtime-types

For the context parameter, the Context type is used, for callback, the ServerlessCallback type is used. These are both available as named exports from @twilio-labs/serverless-runtime-types/types.

The event parameter can be typed manually via an interface or type alias to contain the types that you expect as per the request parameters or POST body defined for the function.

In this case, rather than explicitly typing all three parameters, you’ll use ServerlessFunctionSignature to type handler, which will permit TypeScript to infer the parameters automatically as those types I mentioned above:

import { ServerlessFunctionSignature } from '@twilio-labs/serverless-runtime-types/types';

export const handler: ServerlessFunctionSignature = (context, event, callback) => {
    return callback(null, 'Hello, World!');
}

At this point, you should be able to run npm start. TSC will compile your TypeScript source code and your function should be available via the Twilio Runtime on localhost. The name of the file specifies the location of the function in the URI, so in our case, the function is available at http://locahost:3000/hello-world.

Let’s make a GET Request to the function and ensure we get a “Hello, World!” response back:

curl http://localhost:3000/hello-world ## -> Hello, World!

With that working, we can now integrate Twilio SMS.

Integrating Twilio Programmable SMS

If you don’t already have one, create a free Twilio account and purchase a trial number with SMS capabilities. New Twilio accounts are provided with a 15 USD free credit, so you can complete this tutorial without having to purchase any services. Ensure the phone number has SMS capabilities for your specific region, and if not, enable permissions here.

Using the context object, you can gain access to a pre-initialized Twilio client instance since the Twilio Runtime is aware of your Account SID and Auth Token.

Using this object, you can access the Twilio SMS REST API, which is wrapped by the client. You can go ahead and make the function asynchronous, and then you’ll send an SMS message, specifying a message body, your Twilio phone number, and a target (receiving) phone number:

import { ServerlessFunctionSignature } from '@twilio-labs/serverless-runtime-types/types';

export const handler: ServerlessFunctionSignature = async (context, event, callback) => {
    const twilioClient = context.getTwilioClient();

    try {
        await twilioClient.messages.create({
            body: 'Hello, World from Twilio Functions with TypeScript',
            to: '[Your Phone Number (Format: +11234567890)]',
            from: '[Your Twilio Phone Number (Format: +11234567890)]'
        });

        return callback(null);
    } catch (e) {
        return callback(e);
    }
}

You don’t necessarily have to await the promise settling result of sending the message, but since we are, we’ll wrap the operation in a try/catch block.

If the message is sent correctly, we’ll call the callback, passing null as the first parameter since we don’t have an error object. Otherwise, we’ll pass that error object along. Calling callback ends the request, so you can’t afford not to call it, otherwise, the request will hang.

If you have multiple functions, I’d recommend not repeating the try/catch block everywhere, and opting instead for some kind of withErrorHandling higher-order function that encapsulates your asynchronous and transient requests, watches for errors, and handles them accordingly. This would be considered more “DRY”.

If you run npm start and then make a GET Request to your function, as above (curl [http://localhost:3000/hello-world](http://localhost:3000/hello-world)), your target phone number will receive an SMS message after a short delay.

Deploying your Function

With the function developed and working locally, all you have to now is deploy it with:

npm run deploy

This will fire the predeploy hook to re-compile the project, and then the runtime will use the build/functions files as your functions. Your function URL will be of the form: https://ts-sms-demo-[identifier]-dev.twil.io/hello-world.

Conclusion

We’ve now gone through the process of making TypeScript compatible with Twilio Functions and integrated SMS. Consider taking the project a little further by researching how to make your function respond to POST requests and capture SMS messages from users.

Additionally, taking the following steps may be desirable:

  • Add the build/ directory to your .gitignore so that we can keep the compiled JavaScript out of any git repositories.
  • Consider taking approaches to consolidate error handling so you don’t have to constantly repeat try/catch in your functions.
  • Take a look at the Twilio Functions and Serverless Toolkit documentation.

The Original Article can be found on twilio.com

#typescript #twilio #programming #javascript #web-development

Shawn  Durgan

Shawn Durgan

1595547778

10 Writing steps to create a good project brief - Mobile app development

Developing a mobile application can often be more challenging than it seems at first glance. Whether you’re a developer, UI designer, project lead or CEO of a mobile-based startup, writing good project briefs prior to development is pivotal. According to Tech Jury, 87% of smartphone users spend time exclusively on mobile apps, with 18-24-year-olds spending 66% of total digital time on mobile apps. Of that, 89% of the time is spent on just 18 apps depending on individual users’ preferences, making proper app planning crucial for success.

Today’s audiences know what they want and don’t want in their mobile apps, encouraging teams to carefully write their project plans before they approach development. But how do you properly write a mobile app development brief without sacrificing your vision and staying within the initial budget? Why should you do so in the first place? Let’s discuss that and more in greater detail.

Why a Good Mobile App Project Brief Matters?

Why-a-Good-Mobile-App-Project-Brief-Matters

It’s worth discussing the significance of mobile app project briefs before we tackle the writing process itself. In practice, a project brief is used as a reference tool for developers to remain focused on the client’s deliverables. Approaching the development process without written and approved documentation can lead to drastic, last-minute changes, misunderstanding, as well as a loss of resources and brand reputation.

For example, developing a mobile app that filters restaurants based on food type, such as Happy Cow, means that developers should stay focused on it. Knowing that such and such features, UI elements, and API are necessary will help team members collaborate better in order to meet certain expectations. Whether you develop an app under your brand’s banner or outsource coding and design services to would-be clients, briefs can provide you with several benefits:

  • Clarity on what your mobile app project “is” and “isn’t” early in development
  • Point of reference for developers, project leads, and clients throughout the cycle
  • Smart allocation of available time and resources based on objective development criteria
  • Streamlined project data storage for further app updates and iterations

Writing Steps to Create a Good Mobile App Project Brief

Writing-Steps-to-Create-a-Good-Mobile-App-Project-Brief

1. Establish the “You” Behind the App

Depending on how “open” your project is to the public, you will want to write a detailed section about who the developers are. Elements such as company name, address, project lead, project title, as well as contact information, should be included in this introductory segment. Regardless of whether you build an in-house app or outsource developers to a client, this section is used for easy document storage and access.

#android app #ios app #minimum viable product (mvp) #mobile app development #web development #how do you write a project design #how to write a brief #how to write a project summary #how to write project summary #program brief example #project brief #project brief example #project brief template #project proposal brief #simple project brief template