Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop your first Serverless Component

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

How to develop their first Serverless Component, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Serverless Component operation mechanism

Before we start development, let's take a look at how Serverless Component works:

Each Serverless Component is actually a npm package, which you can install directly through the npm install command. When we execute the command serverless-debug deployment in an application that relies on Serverless Component, it first reads the component parameter in the serverless.yml file to specify the component module, which is automatically installed locally, and then automatically injected into the component module, just like installing the npm package, and executes the default function in the component (described later) to complete the deployment process.

Development steps

The development process of a complete component should include the following process:

Identify functional requirements

Define component configuration: input and output parameters

Component development: default function, remove function (optional)

Test component

Publish the npm package

Next, you will follow the above steps to implement Tencent Cloud CDN components step by step.

1. Identify functional requirements

Tencent Cloud CDN console already provides the ability to configure accelerated domain names manually, but as a lazy programmer, "manual" has always been a problem I try to avoid. So I went to look at the Tencent Cloud documentation to see if the authorities provided a corresponding and convenient way. Sure enough, Tencent Cloud API already provides relevant APIs, so why don't we use API to implement a CDN component that can help us configure automatically?

The need is clear: to develop a component that can automatically configure the CDN accelerated domain name to help us save manual configuration time.

two。 Define component configuration

To add CDN domain names, you need to use two Tencent Cloud API APIs: add accelerated domain names and HTTPS configuration. By reading these two interface documents, a configuration description file config.md is summarized as follows:

MyCDN: component:'@ serverless/tencent-cdn' inputs: host: abc.com hostType: cos origin: www.test.com backupOrigin: www.test.com serviceType: web fullUrl: on fwdHost: ww.test.com cache:-type: 0 rule: all time: 1000-type: 0 rule: all time: 1000 cacheMode: simple refer:-type: 1 list: -'qq.baidu.com' -' * .baidu.com 'accessIp: type: 1 list: -' 1.2.3.4'- '2.3.4.5' https: certId: 123 cert: 123 privateKey: 123 http2: off httpsType: 2 forceSwitch:-2

Inputs is the input parameters of the component, in fact, these parameters are copied from the interface document, the actual development, according to their own component functions, customized configuration is good.

The configurations of the service-free framework are all yaml files, so when defining the component configuration, you need to map the parameters of API to the yaml specification. For example, in the yaml file, symbols-are used to define arrays. If you are not familiar with yaml syntax, you can refer to this YAML language tutorial.

Once the input of the component is defined, you also need to define the output. You only need to roughly organize the API request return structure, and try to be as concise as possible:

{host: 'abc.com', hostId:' 123 'origin:' www.test.com', cname: 'www.test.com.cdn.dnsv1.com', https: true} 3. Component development

For a standard Serverless Component, the structure is as follows:

/ / serverless.jsconst {Component} = require ('@ serverless/core') class MyComponent extends Component {/ * * Default (required) *-default is used to execute, Prepare and update your build function *-execute the command `$ serverless` to run this function *-You can run this function by running the "$serverless" command * / async default (inputs = {}) {return {}} / * * Remove (optional) *-if your component needs to delete infrastructure It is recommended that you add him *-execute the command `$ serverless remove` to run this function * / async remove (inputs = {}) {return {}} / * * Anything (optional) *-if you want to publish components with additional features, you can write the logic in a function The function name can be customized *-execute the command `$ serverless anything` to run this function * / async anything (inputs = {}) {return {}} module.exports = MyComponent

Now that you know the structure of the components, let's start developing.

3.1 initialize the project

Create the project directory tencent-cdn, execute npm init to initialize the project, and enter the relevant information according to the command instructions:

$npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npm help json` for definitive documentation on these fieldsand exactly what they do.Use `npm install `afterwards to install a package andsave it as a dependency in the package.json file.Press ^ C at any time to quit.package name: (cdn-module) tencent-cdnversion: (1.0.0) description: Tencent Cloud CDN Componententry point: (index.js) serverless.jstest command:git repository:keywords: cdn,serverless,serverless-component,serverlesscomponent Tencentauthor: yugasunlicense: (ISC) MITAbout to write to / Users/yugasun/Desktop/Develop/serverless/cdn-module/package.json: {"name": "tencent-cdn", "version": "1.0.0", "description": "Tencent Cloud CDN Component", "main": "serverless.js", "scripts": {"test": "echo\" Error: no test specified\ "& exit 1"}, "keywords": ["cdn" "serverless", "serverless-component", "serverlesscomponent", "tencent"], "author": "yugasun", "license": "MIT"} Is this OK? (yes)

Then create a new serverless.js file and copy the above template code into the serverless.js file.

3.2 write default functions

Default function code, do not post here, a little more o (╯□╰) o.

The main idea is to standardize the interface request parameters according to the inputs input parameters, and then request the interface to perform the configuration.

For Tencent Cloud API, authentication is required for all API requests, so you need to instantiate a Capi first, as follows:

Import {Capi} from'@ tencent-sdk/capi'const capi = new Capi ({SecretId: this.context.credentials.tencent.SecretId, SecretKey: this.context.credentials.tencent.SecretKey, ServiceType: 'cdn',})

Note: the documentation for requesting cloud API library @ tencent-sdk/capi is very comprehensive. Of course, you can also see the source code here.

It needs to pass in three parameters: SecretId, SecretKey, and ServiceType. SecretId and SecretKey can be obtained through this.context.credentials.tencent. When the serverless command is executed, it will be automatically injected into the this.context.credentials.tencent according to the .env file configured in the root directory of the user's project. ServiceType is the current service type, which is defined by Tencent Cloud API. You just need to configure the appropriate parameters for different businesses.

Note: different cloud service providers have different attributes on this.context.credentials. For example, Tencent Cloud is tencent,AWS and aws. The attribute configuration source code of all cloud service providers currently supported can be found here, @ serverless/cli.

Then request to add an accelerated domain name interface:

/ / cdnInputs is the request parameter await AddCdnHost (capi, cdnInputs) we assembled.

Here is a key point: after the API for adding an accelerated domain name is successfully returned, the CDN will not be deployed immediately, which will take time. Therefore, we need to train the status of the newly added domain name in rotation after we implement it. Only when the API is successfully deployed can we proceed with the logic later.

3.3 component state saving

When Serverless Component executes the default function, it will generate some states. For example, after adding a new CDN domain name, it will generate a hostId, which we can save in the this.state object. By executing the this.save () function, it will save the this.state to a file named Template.MyCDN.json in the .serverless folder of the project root directory (MyCDN is the name of the current Serverless application I defined), which is convenient for later use when building and deleting components.

3.4.Writing remove functions

The logic of Serverless Component deletion is that when you use the serverless remove command, it will read the state file saved to .serverless by the default function and inject it into this.state. Then we can remove it according to the value in state. For example, I will use host here, because you need to pass the host parameter to delete the accelerated domain name API.

3.5 complete documentation

The README of open source projects must be written clearly to facilitate the smooth use and development of developers.

4. Test component

At this point, the basic development of our component is completed, and we have to test locally before release. Serverless Framework provides a good local debugging method, that is, the component in the serverless.yml of the application can specify the local project path, for example, under the tencent-cdn directory, create a test folder, and then add the serverless.yml configuration as follows:

MyCDN: component:.. / inputs: host: abc.com...

The.. / here is the relative path, because the serverless.js file of the tencent-cdn component is in the tencent-cdn root directory, and then we can go to the test directory and perform deployment and removal operations to test our component.

Note: although a Serverless Component is a npm module, we can specify any file entry in the project through the main attribute in package.json, but without the serverless.js file, the serverless command cannot be debugged through the local path specified by component.

5. Publish the npm package

To release the npm package, you first need to have a npm account. Please go to the npm official website to register, and then execute npm login locally to log in to your account.

After testing, you can execute npm publish and publish to the npm repository.

Source code

The final implementation source code: @ serverless/tencent-cdn.

Component reference

For each component instance, there will be a load method, which we can use to load other components, as follows:

Const cdnComp = await this.load ('@ serverless/tencent-cdn', 'cdnComp'); is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 219

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report