go-zero/tools/goctl/api/dartgen/genvars.go
Fyn 6a66dde0a1
feat(goctl): api dart support flutter v2 (#1603)
0. support null-safety code gen
1. supports -legacy flag for legacy code gen
2. supports -hostname flag for server hostname
3. use dart official format
4. fix some some bugs

Resolves: #1602
2022-03-04 15:34:13 +08:00

104 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dartgen
import (
"fmt"
"io/ioutil"
"os"
)
const (
varTemplate = `import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../data/tokens.dart';
/// 保存tokens到本地
///
/// 传入null则删除本地tokens
/// 返回true设置成功 false设置失败
Future<bool> setTokens(Tokens tokens) async {
var sp = await SharedPreferences.getInstance();
if (tokens == null) {
sp.remove('tokens');
return true;
}
return await sp.setString('tokens', jsonEncode(tokens.toJson()));
}
/// 获取本地存储的tokens
///
/// 如果没有则返回null
Future<Tokens> getTokens() async {
try {
var sp = await SharedPreferences.getInstance();
var str = sp.getString('tokens');
if (str.isEmpty) {
return null;
}
return Tokens.fromJson(jsonDecode(str));
} catch (e) {
print(e);
return null;
}
}
`
varTemplateV2 = `import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../data/tokens.dart';
const String _tokenKey = 'tokens';
/// Saves tokens
Future<bool> setTokens(Tokens tokens) async {
var sp = await SharedPreferences.getInstance();
return await sp.setString(_tokenKey, jsonEncode(tokens.toJson()));
}
/// remove tokens
Future<bool> removeTokens() async {
var sp = await SharedPreferences.getInstance();
return sp.remove(_tokenKey);
}
/// Reads tokens
Future<Tokens?> getTokens() async {
try {
var sp = await SharedPreferences.getInstance();
var str = sp.getString('tokens');
if (str.isEmpty) {
return null;
}
return Tokens.fromJson(jsonDecode(str));
} catch (e) {
print(e);
return null;
}
}`
)
func genVars(dir string, isLegacy bool, hostname string) error {
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
if !fileExists(dir + "vars.dart") {
err = ioutil.WriteFile(dir+"vars.dart", []byte(fmt.Sprintf(`const serverHost='%s';`, hostname)), 0o644)
if err != nil {
return err
}
}
if !fileExists(dir + "kv.dart") {
tpl := varTemplateV2
if isLegacy {
tpl = varTemplate
}
err = ioutil.WriteFile(dir+"kv.dart", []byte(tpl), 0o644)
if err != nil {
return err
}
}
return nil
}