ibm cloud怎么使用
by Thomas Reinecke
由托马斯·雷内克(Thomas Reinecke)
使用VueJS,FeathersJS和GraphQL快速入门IBM Cloud (Get a rapid start on IBM Cloud with VueJS, FeathersJS, and GraphQL)
Are you looking for a rapid start on playing around with IBMs Cloud? What about taking this opportunity and combining it with some of the latest and greatest technologies for the Web VueJS, FeathersJS and GraphQL? Well then this is a must-read for you to lift-off in less than an hour.
您是否正在寻找开始使用IBM Cloud的快速入门? 抓住这个机会并将其与Web VueJS,FeathersJS和GraphQL的一些最新和最伟大的技术结合起来怎么办? 那么,这是您必须在不到一个小时的时间内完成的必读内容。
What we’ll do:
我们将做什么:
- Overview of the app 应用概述
- create a fresh git repository on GitHub 在GitHub上创建一个新的git存储库
- initialize the frontend app based on Vue CLI 基于Vue CLI初始化前端应用
- initialize the backend app based on FeathersJS CLI 基于FeathersJS CLI初始化后端应用程序
- add GraphQL capabilities to the backend 将GraphQL功能添加到后端
- test the GraphQL API and publish/subscribe 测试GraphQL API并发布/订阅
- add dependencies to the existing frontend app 向现有的前端应用程序添加依赖项
- create a simple SPA thats calling a GraphQL backend 创建一个简单的SPA来调用GraphQL后端
- deployment to IBM’s Cloud 部署到IBM的云
应用概述 (Overview of the App)
在GitHub上创建一个新的git存储库 (Create a fresh git repository on GitHub)
If you don’t yet have a GitHub account, go to github.com and create it. Create yourself a new repository called “VueAndIBMsCloud” (or whatever name you want). Assuming you’re well able to use a console, use the following code to create your first project commit:
如果您还没有GitHub帐户,请访问github.com并创建它。 创建一个名为“ VueAndIBMsCloud”(或所需的任何名称)的新存储库。 假设您能够很好地使用控制台,请使用以下代码创建您的第一个项目提交:
mkdir VueAndIBMsCloud
cd VueAndIBMsCloud
echo "# VueAndIBMsCloud" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/<yourRepo>/VueAndIBMsCloud.git
git push -u origin master
基于Vue CLI初始化前端应用 (Initialise the frontend app based on Vue CLI)
If you need more details to install Vue CLI, work through this article and come back.
如果您需要更多详细信息来安装Vue CLI,请阅读本文并返回。
Installation - Vue.jsVue.js - The Progressive JavaScript Frameworkvuejs.org
安装-Vue.js Vue.js-渐进式JavaScript框架 vuejs.org
Use the vue-cli to initialize a Progressive Web App (PWA)-based “frontend” project:
使用vue-cli初始化基于渐进式Web应用程序(PWA)的“前端”项目:
npm install -g vue-cli
vue init pwa frontend
? Project name frontend
? Project short name: fewer than 12 characters to not be truncated on homescreens (default: same as name)
? Project description A Vue.js project
? Author thomasreinecke <thomas.reinecke@de.ibm.com>
? Vue build runtime
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Setup unit tests with Karma + Mocha? No
? Setup e2e tests with Nightwatch? No
Now compile the project and run it the very first time (instead of “npm” I recommend to use “yarn”):
现在编译项目并第一次运行它(建议使用“ yarn”代替“ npm”):
cd frontend
yarn
yarn dev
Your frontend application is running at http://localhost:8080
您的前端应用程序正在http:// localhost:8080运行
Congratulations, you’ve just created the frontend app based on VueJs.
恭喜,您已经基于VueJs创建了前端应用程序。
基于feathersJS CLI初始化后端应用 (Initialize backend app based on feathersJS CLI)
Use the FeathersJS CLI to initialize the backend project. If you need more details on FeatherJS CLI, use the following link and come back:
使用FeathersJS CLI初始化后端项目。 如果您需要有关FeatherJS CLI的更多详细信息,请使用以下链接并返回:
feathersjs/clicli - The command line interface for scaffolding Feathers applicationsgithub.com
feathersjs / cli cli- 用于 搭建 Feathers应用程序的命令行界面 github.com
npm install -g @feathersjs/cli
mkdir backend
cd backend
feathers generate app
? Project name backend
? Description
? What folder should the source files live in? src
? Which package manager are you using (has to be installed globally)? Yarn
? What type of API are you making? REST, Realtime via Socket.io
yarn start
Your backend application is running at http://localhost:3030/
您的后端应用程序在http:// localhost:3030 /上运行
将GraphQL功能添加到后端 (Add GraphQL capabilities to the backend)
Open Visual Studio Code (or your preferred IDE) > Open… > point it to the folder VueAndIBMsCloud.
打开Visual Studio代码(或您的首选IDE)>打开…>将其指向较早的VueAndIBMs Cloud。
Open backend/src/index.html and replace what’s there with the following code:
打开backend / src / index.html并用以下代码替换其中的内容:
/* eslint-disable no-console */
const logger = require('winston');
const app = require('./app');
const port = app.get('port');
const createSubscriptionServer = app.get('createSubscriptionServer');
// create subscription server and associate it to the server
const server = app.listen(port, () => createSubscriptionServer(server));
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d',
app.get('host'), port)
);
Into the backend/package.json, add the following additional dependencies for GraphQL:
在backend / package.json中 ,为GraphQL添加以下附加依赖项:
"express-session": "1.15.6",
"graphql": "0.12.3",
"graphql-subscriptions": "0.5.6",
"graphql-tools": "2.18.0",
"subscriptions-transport-ws": "0.9.5",
"apollo-server-express": "1.3.2",
Run “yarn” on the command line to pull the additional libraries into your backend project. Now we’re ready to create the Graphql service with some more help of the feather CLI:
在命令行上运行“ yarn”以将其他库拉入您的后端项目。 现在,我们准备在羽化CLI的更多帮助下创建Graphql服务:
feathers generate service
? What kind of service is it? A custom service
? What is the name of the service? graphql
? Which path should the service be registered on? /graphql
You’ll realize a new directory was created: services/graphql.
您将意识到已经创建了一个新目录:services / graphql。
We’re going to create the GraphQL service a little bit differently than the featherJS service template. Go ahead and delete the graphql.hooks.js and graphql.class.js.
我们将创建与featherJS服务模板稍有不同的GraphQL服务。 继续并删除graphql.hooks.js和graphql.class.js。
rm services/graphql/graphql.hooks.js
rm services/graphql/graphql.class.js
Update services/graphql/graphql.service.js with the following code:
使用以下代码更新services / graphql / graphql.service.js :
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express');
const { execute, subscribe } = require('graphql');
const { SubscriptionServer } = require('subscriptions-transport-ws');
const { makeExecutableSchema } = require('graphql-tools');
const TypeDefinitions = require('./graphql.typeDefs');
const Resolvers = require('./graphql.resolvers');
module.exports = function () {
const app = this;
const port = app.get('port');
const schema = makeExecutableSchema({
typeDefs: TypeDefinitions,
resolvers: Resolvers.call(app)
});
// provide endpoint to graphql for the apollo graphql client lib
app.use('/graphql', graphqlExpress((req) => {
return {
schema,
context: {}
};
}));
// provide endpoint to graphiql : the API explorer module
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://localhost:${port}/subscriptions`
}));
// define the API server here
app.set('createSubscriptionServer', function
createSubscriptionServer(server) {
return new SubscriptionServer({
execute, subscribe, schema,
onConnect: () => { console.log('Client Connected'); },
onDisconnect: () => { console.log('Client Disconnected'); }
},
{
server, path: '/subscriptions',
});
});
};
Now create GraphQL typedef and resolvers: create two new files under services/graphql: graphql.typeDefs.js and graphql.resolvers.js and add the following code to it:
现在创建GraphQL typedef和resolvers:在services / graphql下创建两个新文件: graphql.typeDefs.js和graphql.resolvers.js并添加以下代码:
graphql.resolvers.js (graphql.resolvers.js)
const { PubSub } = require('graphql-subscriptions');
const pubsub = new PubSub();
const ITEM_ADDED = 'ITEM_ADDED';
module.exports = function () {
return {
Query: {
Welcome (root, { id }, context) {
return 'Welcome to VueAndIBMsCLoud example';
},
Items (root, { id }, context) {
return [
{
id: 1,
title: 'Item 1',
status: 'open',
created_at: new Date()
},
{
id: 2,
title: 'Item 2',
status: 'closed',
created_at: new Date()
}
];
}
},
Mutation: {
addItem(root, { id, title, status }, context) {
const item = {
id,
title,
status,
created_at: new Date()
};
pubsub.publish(ITEM_ADDED, { itemAdded: item });
return item;
},
},
Subscription: {
itemAdded: {
subscribe: () => pubsub.asyncIterator(ITEM_ADDED),
}
}
};
};
graphql.typeDefs.js (graphql.typeDefs.js)
const typeDefinitions = `
type Item {
id: ID!
title: String
status: String
created_at: String
}
type Query {
Welcome: String,
Items: [Item]
}
type Mutation {
addItem(id: ID!, title: String!, status: String): Item
}
type Subscription {
itemAdded: Item
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
`;
module.exports = typeDefinitions;
Almost there. Let’s add a start script to package.json into the ‘scripts’ section:
差不多了。 让我们在package.json的“ scripts”部分添加一个启动脚本:
"dev": "NODE_ENV=development node src/",
And now run ‘yarn dev’. You should see a message like:info: Feathers application started on http://localhost:3030
现在运行“ yarn dev”。 您应该看到以下消息: info:Feathers应用程序从http:// localhost:3030启动
测试GraphQL API并发布/订阅 (Test the GraphQL API and publish/subscribe)
Try graphiQL as API explorer module http://localhost:3030/graphiq and run a first test like this:
尝试将graphiQL用作API资源管理器模块http:// localhost:3030 / graphiq并运行像这样的第一个测试:
Congratulations, you have included a GraphQL API into your project!
恭喜,您已在项目中包含GraphQL API!
Now let’s test some more complex data fetching:
现在让我们测试一些更复杂的数据获取:
And now let’s test subscription. Open graphiql on a 2nd browser window and setup subscription like this and press the “play” button:
现在让我们测试订阅。 在第二个浏览器窗口中打开graphiql,并设置像这样的订阅,然后按“播放”按钮:
Now back to the first graphiql browser window, enter the following mutation which allows you to add an item to Items array. Since we’ve setup publish/subscribe, we expect to push changes to the Items array to all subscribers:
现在回到第一个graphiql浏览器窗口,输入以下突变,它允许您将一个项目添加到Items数组。 由于我们已经设置了发布/订阅,因此我们希望将对Items数组的更改推送给所有订阅者:
Place both browser windows next to each other and press “Play” on the first window. You’ll realize that the backend server is going to push the data change into your 2nd graphiql window:
将两个浏览器窗口彼此相邻放置,然后在第一个窗口上按“播放”。 您将意识到后端服务器将把数据更改推送到第二个graphiql窗口中:
How cool is that? Congrats, you’ve also setup publish/subscribe based on graphiql on your project.
多么酷啊? 恭喜,您还已经在项目上基于graphiql设置了发布/订阅。
将依赖项添加到前端应用程序 (Add dependencies to the frontend app)
Into the frontend/package.json, add the following additional dependencies to include Graphql, ApolloJS and Subscription support (via Websockets):
在frontend / package.json中 ,添加以下附加依赖项以包括Graphql,ApolloJS和Subscription支持(通过Websockets):
"dependencies": {
"apollo-cache-inmemory": "1.1.5",
"apollo-client": "2.2.0",
"apollo-link": "1.0.7",
"apollo-link-http": "1.3.2",
"apollo-link-ws": "1.0.4",
"apollo-utilities": "1.0.4",
"graphql": "0.12.3",
"graphql-tag": "2.6.1",
"subscriptions-transport-ws": "0.9.5",
"vue": "^2.5.2",
"vue-apollo": "3.0.0-alpha.3",
"vue-router": "^3.0.1"
}
Run “yarn” to pull the dependencies into your frontend project.
运行“ yarn”将依赖项拉入您的前端项目。
cd frontend
yarn
Edit frontend/main.js and replace the code with the following:
编辑frontend / main.js并将代码替换为以下代码:
import Vue from 'vue'
import App from './App'
import router from './router'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { split } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import VueApollo from 'vue-apollo'
// add unified ressource identifiers for Dev and Prod (IBM Cloud)
const uris = {
dev: 'localhost:3030',
prod: 'VueAndIBMsCloud.mybluemix.net'
}
// setup httpLink depending on environment
const httpLink = new HttpLink({
uri: (window.location.hostname === 'localhost') ? `http://${uris.dev}/graphql` : `https://${uris.prod}/graphql`
})
// setup web socket link depending on environment
const wsLink = new WebSocketLink({
uri: (window.location.hostname === 'localhost') ? `ws://${uris.dev}/subscriptions` : `wss://${uris.prod}/subscriptions`,
options: {
reconnect: true
}
})
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
wsLink,
httpLink
)
// define the apolloClient
const apolloClient = new ApolloClient({
link,
cache: new InMemoryCache(),
connectToDevTools: true
})
Vue.use(VueApollo)
const apolloProvider = new VueApollo({
defaultClient: apolloClient
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
apolloProvider,
router,
render: h => h(App)
})
This will prepare your frontend app to use ApolloClient as Library to provide GraphQL Query, Mutation and Subscription support. On the uris object, replace VueAndIBMsCloud.mybluemix.net with your productive deployment target of the backend app.
这将使您的前端应用程序准备好使用ApolloClient作为库来提供GraphQL查询,变异和订阅支持。 在uris对象上,将VueAndIBMsCloud.mybluemix.net替换为后端应用程序的生产性部署目标。
添加UI调用GraphQL后端 (Add UI calling the GraphQL backend)
In your frontend sources, open src/App.vue and replace it with the following code:
在您的前端源代码中,打开src / App.vue并将其替换为以下代码:
<template>
<div id="app">
<h1>{{ welcome }}</h1>
<ul>
<li v-for="(item) of items" v-bind:key="item.id">{{item.title + ' - ' + item.status}}</li>
</ul>
</div>
</template>
<script>
import gql from 'graphql-tag'
export default {
name: 'app',
data () {
return {
welcome: '',
items: []
}
},
mounted () {
this.$apollo.query({
query: gql`query {
Welcome
Items {
id
title
status
}
}`
}).then(({data}) => {
this.welcome = data.Welcome
this.items = data.Items
}).catch((error) => {
console.error(error)
})
},
}
</script>
<style>
body {
margin: 50px;
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
main {
text-align: center;
margin-top: 40px;
}
header {
margin: 0;
height: 56px;
padding: 0 16px 0 24px;
background-color: #35495E;
color: #ffffff;
}
header span {
display: block;
position: relative;
font-size: 20px;
line-height: 1;
letter-spacing: .02em;
font-weight: 400;
box-sizing: border-box;
padding-top: 16px;
}
</style>
Save and run yarn dev to start it. You should now see the new landing page of your frontend app (which does not yet look super exciting, but this is the first time we see data from your graphQL backend in your frontend — isn’t that cool?)
保存并运行yarn dev来启动它。 现在,您应该会看到前端应用程序的新登录页面(看上去还不那么令人兴奋,但这是我们第一次在您的前端中看到来自graphQL后端的数据,这不是很酷吗?)
Now since we have our e2e integration between our frontend and graphQL backend, let’s push it to IBMs cloud and run it there.
现在,由于我们在前端和graphQL后端之间实现了e2e集成,因此让我们将其推送到IBM的云中并在其中运行它。
准备IBM Cloud进行部署 (Preparing IBM Cloud for Deployment)
setup Bluemix CLI on your desktop: https://console.bluemix.net/docs/cli/reference/bluemix_cli/get_started.html#getting-started
在您的桌面上设置Bluemix CLI: https ://console.bluemix.net/docs/cli/reference/bluemix_cli/get_started.html#getting-started
login to IBM’s cloud: bx login
登录到IBM的云: bx登录
set target and space context in IBMs Cloud interactively (go to https://console.bluemix.net/dashboard/apps/ to inspect your options): bx target — cf
在IBM Cloud中以交互方式设置目标和空间上下文(转到https://console.bluemix.net/dashboard/apps/检查您的选项): bx目标— cf
You now should see this:
您现在应该看到:
API endpoint: <your endpoint> (<API version>)
Region: <your region>
User: <your username>
Account: <your account>
Resource group: default
Org: <your org>
Space: <your space>
You have now set the deployment scope for your two apps.
现在,您已经为两个应用程序设置了部署范围。
将后端部署到Bluemix (Deployment of the Backend to Bluemix)
On the backend project, create a new manifest.yml file and enter the following contents into it:
在后端项目上,创建一个新的manifest.yml文件,并在其中输入以下内容:
applications:
- path: .
memory: 1024M
instances: 1
domain: eu-de.mybluemix.net
name: vueAndIbmsCloud-api
host: vueAndIbmsCloud-api
disk_quota: 1024M
Add the following deploy script to package.json to the “scripts” section:
将以下部署脚本添加到package.json的“脚本”部分:
"deploy": "bx cf push vueAndIbmsCloud-api"
(You have to change that app name to make it unique, e.g. append some index of your choice on manifest.yml and package.json.)
(您必须更改该应用程序名称以使其唯一,例如,将您选择的某些索引附加到manifest.yml和package.json上。)
安装BlueMix CLI (Install BlueMix CLI)
https://console.bluemix.net/docs/cli/index.htmlhttps://developer.ibm.com/courses/labs/1-install-bluemix-command-line-interface-cli-dwc020/
https://console.bluemix.net/docs/cli/index.html https://developer.ibm.com/courses/labs/1-install-bluemix-command-line-interface-cli-dwc020/
Run yarn deploy, and this will deploy your backend app to the IBM Cloud.
运行yarn deploy ,这会将您的后端应用程序部署到IBM Cloud。
将前端部署到Bluemix (Deployment of the Frontend to Bluemix)
We deploy the frontend app based on an nginx server, which provides a better performance (in responsetime and throughput) than a node server.
我们基于nginx服务器部署前端应用程序,与节点服务器相比,该应用程序提供了更好的性能(响应时间和吞吐量)。
Depending on what name you picked as your backend deployment target, let’s make sure it’s properly reflected in frontend/src/main.js. In the uris object, replace ‘vueandibmscloud-api.eu-de.mybluemix.net’ with the URL where your backend server is. You can inspect the URL in the Bluemix console > click into your app > view App URL.
根据您选择的名称作为后端部署目标,确保其正确反映在frontend / src / main.js中 。 在uris对象中,将“ vueandibmscloud-api.eu-de.mybluemix.net”替换为后端服务器所在的URL。 您可以在Bluemix控制台中检查URL>单击进入您的应用程序>查看应用程序URL。
On the frontend application root folder, create the manifest.yml and include the following contents:
在前端应用程序的根文件夹上,创建manifest.yml并包括以下内容:
applications:
- path: .
memory: 1024M
instances: 1
domain: mybluemix.net
name: vueAndIbmsCloud
host: vueAndIbmsCloud
disk_quota: 1024M
buildpack: staticfile_buildpack
Add the following deploy script to package.json to the “scripts” section:
将以下部署脚本添加到package.json的“脚本”部分:
"deploy": "npm run build; cp manifest.yml dist/manifest.yml; cd dist; bx cf push vueAndIbmsCloud"
(You have to change that app name to make it unique, e.g. append some index of your choice on manifest.yml and package.json.)
(您必须更改该应用程序名称以使其唯一,例如,在manifest.yml和package.json上附加您选择的一些索引。)
Run yarn deploy, and this will deploy your frontend app to the IBM Cloud.
运行yarn deploy ,这会将您的前端应用程序部署到IBM Cloud。
Congratulations :) You can now use your frontend app on IBM’s Cloud.
恭喜:)您现在可以在IBM的Cloud上使用您的前端应用程序。
Find the sources at GitHub: https://github.com/thomasreinecke/VueAndIBMsCloud
在GitHub上找到源代码: https : //github.com/thomasreinecke/VueAndIBMsCloud
ibm cloud怎么使用