本文整理汇总了TypeScript中co-body类的典型用法代码示例。如果您正苦于以下问题:TypeScript co-body类的具体用法?TypeScript co-body怎么用?TypeScript co-body使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了co-body类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: function
app.use(async function (ctx: koa.Context, next: Function): Promise<void> {
var body: any;
// application/json
body = await parse.json(ctx.req);
// explicit limit
body = await parse.json(ctx.req, { limit: '10kb' });
// application/x-www-form-urlencoded
body = await parse.form(ctx.req);
// text/plain
body = await parse.text(ctx.req);
// either
body = await parse(ctx.req);
// custom type
body = await parse(ctx.req, { textTypes: ['text', 'html'] });
// This lib also supports ctx.req in Koa (or other libraries), so that you may simply use this instead of this.req.
// application/json
body = await parse.json(ctx);
// application/x-www-form-urlencoded
body = await parse.form(ctx);
// text/plain
body = await parse.text(ctx);
// either
body = await parse(ctx);
});
示例2: async
export const createItem = async (ctx: Router.IRouterContext, next: () => void) => {
try {
const todo = await parse(ctx);
const userId = ctx.state.userId;
if (!userId || !todo) {
ctx.throw(400, 'userId and a TODO item are required');
}
const result = await r.table(TABLE_NAME).insert(
r.expr(todo).merge({
userId,
archived: false,
createdAt: r.now(),
updatedAt: r.now(),
}),
{ returnChanges: true }
)
.run()
.then((response: any) => {
return response.changes[0].new_val;
});
console.log(result);
// result = (result.changes.length > 0) ? result.changes[0].new_val : {}; // customer now contains the previous customer + a field `id` and `createdAt`
ctx.body = JSON.stringify(result);
}
catch (e) {
ctx.status = 500;
ctx.body = e.message;
}
};
示例3: async
export const login = async (ctx: Router.IRouterContext, next: () => void) => {
try {
const auth = await parse(ctx);
const user: User = await userDbInstance.findOne({ email: auth.email, password: auth.password });
if (!user) {
ctx.status = 401;
return ctx.body = { error: true, message: 'Wrong email and/or password' };
}
return ctx.body = JSON.stringify({ token: createJWT(user) });
} catch (e) {
return ctx.throw(500, e.message);
}
};
示例4: async
export const update = async (ctx: Router.IRouterContext, next: () => void) => {
try {
const customer = await parse(ctx);
const id = customer.id;
const result = await r.table(TABLE_NAME)
.get(id)
.update(r.object(customer).merge({
updatedAt: r.now(),
}), { returnChanges: true })
.run()
.then((response: any) => {
return response.changes[0].new_val;
});
// result = (result.changes.length > 0) ? result.changes[0].new_val : {};
// ctx.body = JSON.stringify(result);
}
catch (e) {
ctx.status = 500;
ctx.body = e.message;
}
};
示例5: async
export const authenticate = async (ctx: Router.IRouterContext, next: (arg: any) => void) => {
let token = '';
try {
let auth: TwitterOauth;
if (!!ctx.headers['content-type']) {
auth = await parse(ctx);
}
const requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
const accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
const profileUrl = 'https://api.twitter.com/1.1/users/show.json?screen_name=';
// Part 1 of 2: Initial request from Satellizer.
if (!auth.oauth_token || !auth.oauth_verifier) {
const requestTokenOauth = {
consumer_key: config.TWITTER_KEY,
consumer_secret: config.TWITTER_SECRET,
callback: config.TWITTER_CALLBACK
};
// Step 1. Obtain request token for the authorization popup.
const obtainResponse = await request(requestTokenUrl, { method: 'POST', oauth: requestTokenOauth });
const oauthToken = qs.parse(obtainResponse.body);
// Step 2. Send OAuth token back to open the authorization screen.
ctx.body = JSON.stringify(oauthToken);
} else {
// Part 2 of 2: Second request after Authorize app is clicked.
const accessTokenOauth = {
consumer_key: config.TWITTER_KEY,
consumer_secret: config.TWITTER_SECRET,
token: auth.oauth_token,
verifier: auth.oauth_verifier
};
// Step 3. Exchange oauth token and oauth verifier for access token.
const exchangeResponse = await request(accessTokenUrl, { method: 'POST', oauth: accessTokenOauth });
const accessToken = qs.parse(exchangeResponse.body);
const profileOauth = {
consumer_key: config.TWITTER_KEY,
consumer_secret: config.TWITTER_SECRET,
oauth_token: accessToken.oauth_token
};
// Step 4. Retrieve profile information about the current user.
const response = await request(profileUrl + accessToken.screen_name, { method: 'GET', oauth: profileOauth, json: true });
const profile = response.body;
// Step 5a. Link user accounts.
if (ctx.headers.authorization) {
const existingUser = await userDbInstance.findOne({ twitter: profile.id });
if (existingUser) {
ctx.status = 409;
return ctx.body = { error: true, message: 'There is already a Twitter account that belongs to you' };
}
token = ctx.headers.authorization.split(' ')[1];
const payload = decode(token, config.TOKEN_SECRET);
const user = await userDbInstance.findById(payload.sub);
if (!user) {
ctx.status = 400;
return ctx.body = { error: true, message: 'User not found' };
}
user.twitter = profile.id;
user.displayName = user.displayName || profile.name;
user.picture = user.picture || profile.profile_image_url.replace('_normal', '');
const outputUser = await userDbInstance.save(user);
token = createJWT(outputUser);
return ctx.body = JSON.stringify({ token });
} else {
// Step 5b. Create a new user account or return an existing one.
const existingUser = await userDbInstance.findOne({ twitter: profile.id });
if (existingUser) {
token = createJWT(existingUser);
return ctx.body = JSON.stringify({ token });
}
const user = {
// email: profile.email, // twitter doesn't provide email
twitter: profile.id,
picture: profile.profile_image_url.replace('_normal', ''),
displayName: profile.name
};
const updatedUser = await userDbInstance.save(user);
token = createJWT(updatedUser);
return ctx.body = JSON.stringify({ token });
}
}
} catch (e) {
return ctx.throw(500, e.message);
}
};
示例6: async
export const authenticate = async (ctx: Router.IRouterContext, next: (arg: any) => void) => {
let token = '';
try {
const auth = await parse(ctx);
const accessTokenUrl = 'https://github.com/login/oauth/access_token';
const userApiUrl = 'https://api.github.com/user';
const params = {
code: auth.code,
client_id: auth.clientId,
client_secret: config.GITHUB_SECRET,
redirect_uri: auth.redirectUri
};
// Step 1. Exchange authorization code for access token.
const getResponse1 = await request(accessTokenUrl, { method: 'GET', qs: params });
const accessToken = qs.parse(getResponse1.body);
const headers = { 'User-Agent': 'Aurelia' };
// Step 2. Retrieve profile information about the current user.
const getResponse2 = await request(userApiUrl, { method: 'GET', qs: accessToken, headers, json: true });
const profile = getResponse2.body;
if (getResponse2.statusCode !== 200) {
ctx.status = 500;
return ctx.body = { error: true, message: profile.error.message };
}
// Step 3a. Link user accounts.
if (ctx.headers.authorization) {
const existingUser: User = await userDbInstance.findOne({ github: profile.id });
if (existingUser) {
ctx.status = 409;
return ctx.body = { error: true, message: 'There is already a Github account that belongs to you' };
}
token = ctx.headers.authorization.split(' ')[1];
const payload = decode(token, config.TOKEN_SECRET);
const user: User = await userDbInstance.findById(payload.sub);
if (!user) {
ctx.status = 400;
return ctx.body = { error: true, message: 'User not found' };
}
user.email = profile.email;
user.github = profile.id;
user.picture = user.picture || profile.avatar_url + '&size=200';
user.displayName = user.displayName || profile.name;
const outputUser = await userDbInstance.save(user);
token = createJWT(outputUser);
return ctx.body = JSON.stringify({ token });
} else {
// Step 3b. Create a new user account or return an existing one.
const existingUser: User = await userDbInstance.findOne({ github: profile.id });
if (existingUser) {
token = createJWT(existingUser);
return ctx.body = JSON.stringify({ token });
}
const user = {
email: profile.email,
github: profile.id,
picture: profile.avatar_url + '&size=200',
displayName: profile.name
};
const updatedUser: User = await userDbInstance.save(user);
token = createJWT(updatedUser);
return ctx.body = JSON.stringify({ token });
}
} catch (e) {
return ctx.throw(500, e.message || e);
}
};
示例7: async
export const authenticate = async (ctx: Router.IRouterContext, next: (arg: any) => void) => {
let token = '';
try {
const auth = await parse(ctx);
const accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';
const peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';
const params = {
code: auth.code,
client_id: auth.clientId,
client_secret: config.GOOGLE_SECRET,
redirect_uri: auth.redirectUri,
grant_type: 'authorization_code'
};
// Step 1. Exchange authorization code for access token.
const postResponse = await request(accessTokenUrl, { method: 'POST', json: true, form: params });
const accessToken = postResponse.body.access_token;
const headers = { Authorization: 'Bearer ' + accessToken };
// Step 2. Retrieve profile information about the current user.
const getResponse = await request(peopleApiUrl, { method: 'GET', headers, json: true });
const profile = getResponse.body;
// Step 3a. Link user accounts.
if (ctx.headers.authorization) {
const existingUser: User = await userDbInstance.findOne({ google: profile.sub });
if (existingUser) {
ctx.status = 409;
return ctx.body = { error: true, message: 'There is already a Google account that belongs to you' };
}
token = ctx.headers.authorization.split(' ')[1];
const payload = decode(token, config.TOKEN_SECRET);
const user: User = await userDbInstance.findById(payload.sub);
if (!user) {
ctx.status = 400;
return ctx.body = { error: true, message: 'User not found' };
}
user.google = profile.sub;
user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200');
user.displayName = user.displayName || profile.name;
const outputUser: User = await userDbInstance.save(user);
token = createJWT(outputUser);
return ctx.body = JSON.stringify({ token });
} else {
// Step 3b. Create a new user account or return an existing one.
const existingUser: User = await userDbInstance.findOne({ google: profile.sub });
if (existingUser) {
token = createJWT(existingUser);
return ctx.body = JSON.stringify({ token });
}
const user = {
email: profile.email,
google: profile.sub,
picture: profile.picture.replace('sz=50', 'sz=200'),
displayName: profile.name
};
const updatedUser: User = await userDbInstance.save(user);
token = createJWT(updatedUser);
return ctx.body = JSON.stringify({ token });
}
} catch (e) {
return ctx.throw(500, e.message);
}
};